从文件中读取数据
类似于将数据存储到文件中,Context 类中还提供了一个 openFileInput() 方法,用于从文件中读取数据。
openFileInput() 方法只接收一个参数,即要读取的文件名,然后系统会自动到 /data/data/<包名>/files/ 目录下去加载这个文件,并返回一个 FileInputStream 对象。
展示如何从文件中读取文本数据:
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
//设置将要打开的存储文件名称
in = openFileInput("data");
//FileInputStream -> InputStreamReader ->BufferedReader
reader = new BufferedReader(new InputStreamReader(in));
String line = new String();
//读取每一行数据,并追加到StringBuilder对象中,直到结束
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();
}
技巧:判断字符串为空(字符串为空值,或者空字符串)的小工具 TextUtils.isEmpty( )方法。它可以进行两种空值的判断,当传入的字符串等于null或者等于空字符串的时候,这个方法就会返回 true,从而不用担心使用未实例化的字符串而产生的空指针异常了。
文件存储方面的核心技术就是 Context 类中提供的 openFileInput() 和 openFileOutput() 方法,之后就是利用Java的各种IO流来进行读写操作就可以了。
(Android中直接使用Java的IO流也是可以的,但是记住加上 WRITE_EXTERNAL_STORAGE 和 MOUNT_UNMOUNT_FILESYSTEMS 权限声明)