你可以使用
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) {