写入内部存储

时间:2018-05-14 11:32:15

标签: java android

有没有办法在Android内部存储中编写?我在谷歌开发者网站上尝试了以下内容 -

File file = new File(context.getFilesDir(), filename);

String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;

try {
    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    outputStream.write(fileContents.getBytes());
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

问题是每当我卸载应用程序时,文件也会被删除。但是,即使在卸载应用程序后,我仍需要保留该文件...

2 个答案:

答案 0 :(得分:1)

您必须定义尝试创建的文件类型。

FileType =“image”;    FileType =“text”;

在代码中定义文件类型。

答案 1 :(得分:0)

当您使用context.getFilesDir()时,您正在访问项目文件目录。如果您想在外部保存,则应使用类似Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS)的内容,并在Android Manifest中使用权限:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

您可以查找其他目录here