我正在开发一个应用程序,该应用程序在两个.xml文件中存储少量设置,保存在内部存储中。我需要将它们保存在那里,所以请不要回答我“将它们保存在SD卡上”。
我尝试卸载然后重新安装(从Android Studio)我的应用程序以查看android:allowBackup="true"
是否也适用于内部存储文件,但答案是否定的。
这是因为我是从IDE重新安装还是需要在某处添加一些代码?
感谢您的帮助。
答案 0 :(得分:1)
您可以使用Environment.getExternalStorageDirectory()
保存这些文件。它存储在外部存储设备上。不要把外部存储这个术语搞砸为SD卡。 SD卡是辅助外部存储。但是Environment.getExternalStorageDirectory()
会返回设备主外部存储的顶级目录,该目录基本上是一个不可移动的存储。
因此文件路径可以是/storage/emulated/0/YOURFOLDER/my.xml
因此,即使您卸载了该应用,也不会删除这些文件。
您可以使用此代码段在主外部存储空间中创建文件:
private final String fileName = "note.txt";
private void writeFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Save to: " + path);
String data = editText.getText().toString();
try {
File myFile = new File(path);
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
不要忘记在Android Manifest中添加以下权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
然后您可以按如下方式阅读该文件:
private void readFile() {
File extStore = Environment.getExternalStorageDirectory();
// ==> /storage/emulated/0/note.txt
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i("ExternalStorageDemo", "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "\n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}