第六章《第一行代码》1.文件存储

我博客的相关说明

持久化技术

《第一行代码》第六章学习笔记

主要介绍三种方式

1.将数据存储到文件中

1.1示例以及前期准备

Context类当中提供了一个openFileOutput()方法,用于将数据存储到指定文件中。

接收

openFileOutput()方法接收两个参数:
1.文件名——在文件创建时候使用的名称。~文件名不可以包含路径;所有文件统一储存到/data/data/<package name>/files/目录下 ~
2.文件的操作模式 主要有两种可选
MODE_PRIVATE 默认操作模式,当指定文件名相同,新写入内容覆盖原内容
MODE_APPEND 若该文件已经存在,则往文件里追加内容

返回值

openFileOutput()方法的返回值是一个FileOutputStream对象
得到这个对象之后,可以用Java流的方式将数据写到文件当中

代码示例:

public void save(){
	String data = "Date to save";
	FileOutputStream out = null;
	BufferedWriter writer = null;
	try{
		out = openFileOutput("data",Context.MODE_PRIVATE);
		writer = new BufferedWriter(new OutputStreamWriter(out));
		writer.write(data);
	}catch (IOException e){
		e.printStackTrace();
	}finally{
		try{
			if (writer != null){
				writer.close();i
			}
		}catch (IOException e){
			e.printStackTrace();
		}
	}
}

这里通过openFileOutput("data",Context.MODE_PRIVATE);方法来得到一个FileOutputStream对象→out,再通过out构建出一个OutputStreamWruter(out)对象,再使用这个对象构建出BufferedWriter对象writer,从而我们便可以通过writer把文本内容写到文件当中了。

1.2 Android代码

1.2.1存储数据

在布局文件中加入一个EditText组件,用于获取文本内容:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="10dp">

    <EditText
        android:id="@+id/main_EDT"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="输入保存文本"/>
        
</RelativeLayout>

预览:
预览1
之后我们在MainActivity当中修改代码:

public class MainActivity extends AppCompatActivity {
    private EditText edt_save;   //声明控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt_save = findViewById(R.id.main_EDT);  //找到控件
        /*旧版AS在FindViewById前加键值转换(EditText)*/
    }

    @Override
    protected void onDestroy() {
        /*重写方法后可以保证在活动被销毁的时候save方法一定被执行*/
        super.onDestroy();
        String inputText = edt_save.getText().toString();
        save(inputText);
    }

    public void save(String Input){
        FileOutputStream out = null;
        BufferedWriter writer = null;
        try{
            out = openFileOutput("data", Context.MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(out));
            writer.write(Input);
        }catch (IOException e){
            e.printStackTrace();
        }finally{
            try{
                if (writer != null){
                    writer.close();
                }
            }catch (IOException e){
                e.printStackTrace();
            }
        }
    }
}

将程序运行到手机,在EditText中输入数据,在按返回键,EditText当中的数据便被保存了!
怎么查看呢? 可以借助Android Device Monitor工具来查看
点击AndroidStudio导航栏中的Tools→Android,找到Android Device Monitor。进入工具后,找到File Explorer标签页,在这里找到/data/data/com.example.filepersistencetest/files/目录,就可以看到生成了一个data文件。(AS3.0之后的版本参考这篇文章进入Android Device Monitor

1.2.2从文件读取数据

与存储文件类似,Context类中还提供了openFileInput()方法,用于从文件中读取数据。

接收

openFileInput()方法接收一个参数:
调取文件的文件名:~系统会自动到/data/data/<package name>/files/目录下去加载这个文件~

返回值

openFileInput()方法的返回值是一个FileOutputStream对象
得到这个对象之后,便可通过Java流的方式将文件读取出来了

代码示例:

 public String load(){
        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 {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content.toString();
    }

这里首先通过openFileInput("data")方法找到一个FileInputStream对象in然后又借助in对象构建出一个InputStreamReader(in)对象,接着用InputStreamReader(in)对象构建出一个BufferedReader对象reader,这样我们就可以通过reader对象来进行一行一行的读取。再将读取出的内容存放到一个StringBuilder对象中,然后再将内容返回就🆗了。

之后,修改MainActivity中的代码:

public class MainActivity extends AppCompatActivity {
    private EditText edt_save;   //声明控件
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edt_save = findViewById(R.id.main_EDT);  //找到控件
        /*旧版AS在FindViewById前加键值转换(EditText)*/
        String inputText = load();
        if (!TextUtils.isEmpty(inputText)){
            edt_save.setText(inputText);
            edt_save.setSelection(inputText.length());
            Toast.makeText(this,"读取成功!",Toast.LENGTH_SHORT);
        }
    }

    @Override
    protected void onDestroy() {
     ......}

    public void save(String Input){
    ......}

    public String load(){
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try{
            in = openFileInput("aabbc");
            reader = new BufferedReader(new InputStreamReader(in));
            String line = " ";
            while ((line = reader.readLine()) != null){
                content.append(line);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return content.toString();
    }
}

可以看到在onCreate()方法中,调用了load()方法来获取存储文件中的内容,如果,读到的内容不为null,则调用EditText中的setText()方法将内容填充到EditText当中。
并且调用setSelection()方法将光标移动到文末。
注意:TextUtils.isEmpty()方法可以一次性进行两次空值判断:1.传入的字符串等于null 2.传入的字符串为空字符串 这两种情况都会返回 true

文件存储的核心技术在于使用Context中的openFileOutput() 和openFileInput()方法,并利用Java流的方式进行读写操作。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值