文件储存是android中最基本的一种数据储存方式,不对存储内容进行任何格式化处理,所有数据都是原封不动的保存到文件当中。因此,适合用于储存一些简单的文本数据或者二进制数据。

Content类中提供了一个openFileOutput(),可以将数据储存到指定文件中。

第一个是文件名(不包含路径)。

第二个是操作模式:

MODE_PRIVATE 表示文件名相同是,覆盖原文件的内容。

MODE_APPEND 表示如果该文件已经存在,就往文件中追加内容,不存在就创建新文件。

展示如何保存一个文本内容到文件中:

private void save(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();
            }
        }
    }

通过openFileOutput()方法得到一个FileOutputStream对象,在借助它构建一个OutputStreamWriter对象,接着再使用OutPutStreamWriter构建出一个BufferedWriter对象,这样就可以通过BufferedWriter来将本文内容写入到文件中。

XML文件中:

<EditText
        android:id="@+id/edit"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:hint="输入内容" />

我们只需要一个EditText来测试,id为edit。当我们在文本框输入内容在按下Back键时,这时候数据就丢失了,因为这是一个瞬时数据,在活动被撤销时候就会被回收掉。我们要在它回收之前,将它存储到文件当中。

MainActivity中:

public class MainActivity extends AppCompatActivity {

    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit = (EditText) findViewById(R.id.edit);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        save(inputText);
    }

    private void save(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();
            }
        }
    }
}

首先我们要在onDestory()中来写。保证在销毁之前调用存储数据的方法。如一开始所说,按照方法把文件储存在名“data”的文件中。

运行程序然后输入任意内容之后按下back键,这时,输入的内容就已经被存储到文件中了。

点击Android Studio 导航栏中的Toos   然后 Android就可以打开Android Device Monitior工具。然后进入File Explorer找到/data/data/com.example.filepersistencetest/files目录就可以看到生成了一个data文件,导出然后记事本打开就能看到内容。

将数据保存下来之后要想办法在下次启动时候再将数据还原到EditText中。

Content来中还有一个openFileInput()方法,用于在文件中读取数据,只有一个参数,文件名。系统会自动根据文件名去目录下加载与文件名相对的文件;

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

如上,首先通过openFileInput() 方法获取一个FileInputStream对象,然后在构建出一个

InputStreamReader对象,在使用 InputStreamReader构建出BufferedReader对象,通过 BufferedReader进行一行行读取不能够存放在StringBuilder 对象中。

以下是从输入到重新获取的全部代码:

import android.content.Context;
import .AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity {

    private EditText edit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edit = (EditText) findViewById(R.id.edit);
        String inputText = load();
        if (!TextUtils.isEmpty(inputText)) {
            edit.setText(inputText);
            // 光标的位置
            edit.setSelection(inputText.length());
            Toast.makeText(this, "成功获取数据", Toast.LENGTH_SHORT).show();
        }
    }

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

    @Override
    protected void onDestroy() {
        super.onDestroy();
        String inputText = edit.getText().toString();
        save(inputText);
    }

    private void save(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();
            }
        }
    }
}

可以看到在onCreate()方法中调用了load()方法来读取文本内容,如果不为空就调用setTexe()讲内容填充进去,并且把光标的位置设置到末尾。最后Toast一句提示。


TextUtils.isEmpty()是用于一次性进行两种空值判断,当传入的字符串等于null或者为空时都会返回true。