案例分析:FilePersistenceTest

在EditText中输入文本内容,退出应用程序或者 单击“保存”按钮时

保存EditText中的数据到名 为“data”的文件中。

打开Device File Explorer,该文件应该存于 /data/data/cn.edu.hunnu.filepersistencetest/files/ 目录

MainActivity.java

package cn.edu.hunnu.filepersisttest;import android.content.Context;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;public class MainActivity extends AppCompatActivity {private EditText edit;private Button bt_save_in;private Button bt_read_in;private Button bt_save_out;private Button bt_read_out;private Button bt_clr_edit;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit = (EditText)findViewById(R.id.edit);bt_clr_edit = (Button)findViewById(R.id.bt_clr_edit);bt_clr_edit.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {edit.setText("");}});bt_save_in = (Button)findViewById(R.id.bt_save_in);bt_save_in.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = edit.getText().toString();saveToInternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to internal storage succeeded",Toast.LENGTH_SHORT).show();}});bt_read_in =(Button)findViewById(R.id.bt_read_in);bt_read_in.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = loadFromInternalStorage();if (!TextUtils.isEmpty(inputText)) {edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(MainActivity.this, "Restoring from internal storage succeeded", Toast.LENGTH_SHORT).show();}}});bt_save_out = (Button)findViewById(R.id.bt_save_out);bt_save_out.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = edit.getText().toString();saveToExternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to external storage succeeded",Toast.LENGTH_SHORT).show();}});bt_read_out = (Button)findViewById(R.id.bt_read_out);bt_read_out.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View view) {String inputText = loadFromExternalStorage();if (!TextUtils.isEmpty(inputText)) {edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(MainActivity.this, "Restoring from external storage succeeded", Toast.LENGTH_SHORT).show();}}});}public void saveToInternalStorage(String inputText) {FileOutputStream out = null;BufferedWriter writer = null;try {out = openFileOutput("data", Context.MODE_PRIVATE);writer = new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (IOException e) {e.printStackTrace();} finally {try {if (writer != null) {writer.close();}} catch (IOException e) {e.printStackTrace();}}}public String loadFromInternalStorage() {FileInputStream in = null;BufferedReader reader = null;StringBuilder content = new StringBuilder();try {in = openFileInput("data");reader = new BufferedReader(new InputStreamReader(in));String line = "";while ((line = reader.readLine()) != null) {content.append(line);}} catch (IOException e) {e.printStackTrace();} finally {if (reader != null) {try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}public void saveToExternalStorage(String inputText) {String environment = Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(environment)) {//外部设备可以进行读写操作//保存在外部存储根目录,卸载应用时不能删除该文件//File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");//保存在外部私有目录,卸载时会同时删除该文件String sd_path = this.getExternalFilesDir("").getAbsolutePath();Log.e("MainActivity+",sd_path);File file = new File(sd_path);if(!file.exists()){//判断文件目录是否存在file.mkdirs();}file = new File(sd_path,"text.txt");FileOutputStream fos;try{//写入数据fos = new FileOutputStream(file);OutputStreamWriter  osw = new OutputStreamWriter(fos);osw.write(inputText);osw.flush();osw.close();fos.close();}catch(Exception exception){exception.printStackTrace();}}}public String loadFromExternalStorage() {String content = null;String environment = Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(environment)) {
//            File sd_path = Environment.getExternalStorageDirectory();
//            Log.e("MainActivity",sd_path.toString());
//            File file = new File(sd_path,"test.txt");String sd_path = this.getExternalFilesDir("").getAbsolutePath();File file = new File(sd_path,"text.txt");Log.e("MainActivity+",file.getPath());FileInputStream fis;try{//读取文件fis = new FileInputStream(file);InputStreamReader  isr = new InputStreamReader(fis,"UTF-8");char[] input = new char[fis.available()];isr.read(input);content = new String(input);isr.close();fis.close();}catch(Exception exception){exception.printStackTrace();}}return content;}@Overrideprotected void onDestroy() {super.onDestroy();String inputText = edit.getText().toString();saveToInternalStorage(inputText);Toast.makeText(MainActivity.this,"Save to internal storage succeeded",Toast.LENGTH_SHORT).show();}
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:padding="5dp"android:orientation="vertical"tools:context=".MainActivity"><EditTextandroid:id="@+id/edit"android:layout_width="match_parent"android:layout_height="wrap_content"android:ems="10"android:hint="Type something here" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/bt_save_in"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="保存(内部存储)" /><Buttonandroid:id="@+id/bt_read_in"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="读取(内部存储)" /></LinearLayout><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:orientation="horizontal"><Buttonandroid:id="@+id/bt_save_out"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="保存(外部存储)" /><Buttonandroid:id="@+id/bt_read_out"android:layout_width="0dp"android:layout_height="wrap_content"android:layout_weight="1"android:text="读取(外部存储)" /></LinearLayout><Buttonandroid:id="@+id/bt_clr_edit"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="清空输入框" /></LinearLayout>

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.example.filepersisttest"><uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permission android:name = "android.permission. READ_EXTERNAL_STORAGE"/><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:roundIcon="@mipmap/ic_launcher_round"android:supportsRtl="true"android:theme="@style/AppTheme"><activity android:name=".MainActivity"><intent-filter><action android:name="android.intent.action.MAIN" /><category android:name="android.intent.category.LAUNCHER" /></intent-filter></activity></application></manifest>

Android 数据存储-内外部存储测试相关推荐

  1. android数据储存之存储方式

    可以将数据储存在内置或可移动存储,数据库,网络,sharedpreference. android可以使用Content provider来使你的私有数据暴漏给其他应用程序. 一.sharedpref ...

  2. android数据存放map_Android存储数据到本地文件

    xml文件 xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_pare ...

  3. Android数据持久化

    Android数据持久化(存储) 1.SharedPreferences SharedPreferences是Android提供的数据持久化的一种手段,适合单进程.小批量的数据存储与访问.Shared ...

  4. Android数据存储五种方式总结

    1 使用SharedPreferences存储数据     2 文件存储数据       3 SQLite数据库存储数据 4 使用ContentProvider存储数据 5 网络存储数据 下面详细讲解 ...

  5. Android数据存储(3):External Storage

    Android系统的数据存储第三种方式是External Storage,即是外部存储. 外部存储通常存储的是公共的数据,存储位置是在扩展卡或SD卡上,存储目录:/mnt/sdcard/Android ...

  6. Android数据存储安全规范

    标题理论概述 存储数据对于移动应用程序至关重要,应将尽可能少的敏感数据存储在永久性本地存储中,但是在大多数实际场景中,必须存储某种类型的用户数据.如果敏感数据没有受到应用程序适当保护,就很容易受到攻击 ...

  7. Android数据存储几种方式用法总结

    Android数据存储几种方式用法总结 1.概述 Android提供了5种方式来让用户保存持久化应用程序数据.根据自己的需求来做选择,比如数据是否是应用程序私有的,是否能被其他程序访问,需要多少数据存 ...

  8. android平台上持久化存储3种手段_Android 数据持久化==存储数据的五种方法

    1.使用SharedPreferences存储数据 2.文件存储数据 3.SQLite数据库存储数据 4.使用ContentProvider存储数据 5.网络存储数据 第一种: 使用SharedPre ...

  9. android模拟器的数据存放,Android模拟器在哪里存储SQLite数据库?

    Android模拟器在哪里存储SQLite数据库? 我正在开发一个将数据存储在SQLite数据库中的Android应用程序. 我的问题是,当您使用模拟器时,此数据库文件存储在文件系统中的哪个位置? 我 ...

最新文章

  1. 目录遍历漏洞:入侵检测php程序中的目录遍历漏洞,目录浏览(目录遍历)漏洞
  2. 【Centos】Centos7.5取消自动锁屏功能
  3. 封装javascript分页插件——可以使用的测试版(β版)
  4. 上天入海又怎样?阿里的运动达人纷纷表示不服
  5. 【LeetCode笔记】139. 单词拆分(Java、动态规划、字符串、哈希表)
  6. 阿里技术:如何画出一张合格的技术架构图?
  7. asp.net findcontrol html控件,findcontrol-在ASP.NET中查找控件的更好方法
  8. java集合类练习_JAVA集合类练习
  9. VB判断指定的WORD文档是否被打开
  10. jfreechart的时序图(曲线图)运行时间长了就变的很卡
  11. 网规:第1章计算机网络原理-1.4网络设备与网络软件
  12. 【java笔记】常用函数式接口(3):Predicate接口
  13. Java并发编程75道面试题及答案 1
  14. 硬件探索——STM32F4通过SPI总线读取GMR(磁编码器)
  15. JDK动态代理简单实现
  16. 反射(filed)的理解
  17. 中学计算机论文题目,中学计算机相关论文题目 中学计算机论文标题如何定
  18. 能耗在线监测系统在酒店节能管理中的应用
  19. 京东网站页面编写(HTML、CSS、JS),包括京东秒杀的倒计时、轮播图等功能
  20. 在mac电脑上,用Safari浏览器调试ios手机移动端页面

热门文章

  1. [源码和文档分享]基于java 的仿QQ聊天工具
  2. VS2013\VS2017 使用git 总是需要输入账号密码
  3. GARFIELD@11-07-2004
  4. 一句话说清聚集索引和非聚集索引以及MySQL的InnoDB和MyISAM
  5. Http环境下的保持连接方式
  6. C# ref和out关键字
  7. 带闰年判断的正则表达式
  8. .NET中的密码学--对称加密
  9. 使用 Vml 制作立体柱状投票统计图的完整程序
  10. 运用.NET读写Windows注册编辑表