//写入数据
public void save(String inputText) {
FileOutputStream out = null;
BufferedWriter writer = null;
try {
/**
* MODE_PRIVATE 默认模式,其中创建的文件只能由调用应用程序(或共享相同用户ID的所有应用程序)访问
* 当指定同样文件名的时候,所写入的内容将会覆盖原文件中的内容
*/
out = openFileOutput("data2.txt", Context.MODE_PRIVATE);
//通过OutputStreamWriter转换流,把输出字节流转换成输出字符流
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
writer.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
已经写入数据的文件位置在data/data/包名/files目录下,如果要查看文件,如图找到Device File Explorer,我的Android Studio版本是3.2
倘若没发现files目录,可以同步更新试试
看不懂文件权限的推荐一篇博文Linux中drwxr-xr-x.的意思和权限
//读取数据
public String load() {
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
try {
in = openFileInput("data2.txt");
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();
}