openFileOutput:如何在/data/data/路径之外创建文件

3
我想知道你是否能帮我解答这个问题。我不明白如何访问例如“下载”文件夹或一些我自己的文件夹。
我想创建一些txt文件并通过USB访问它。我没有找到与我的问题相关的主题,因为我不知道我在哪里搜索。
        String string = "hello world!";

        FileOutputStream fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();

感谢您的提示 :)
1个回答

7

首先阅读有关文件存储选项的官方文档。请记住,外部存储并不等同于“可移动SD卡”。它同样可以是您Nexus设备上的32GB或其他内存。

以下是获取文件目录基础文件夹的示例(即在卸载应用程序时被删除的文件夹,与缓存文件夹不同,即使在卸载后仍然存在):

String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    baseFolder = context.getExternalFilesDir(null).getAbsolutePath()
}
// revert to using internal storage
else {
    baseFolder = context.getFilesDir().getAbsolutePath();
}

String string = "hello world!";
File file = new File(basefolder + "test.txt");
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.close();

更新:由于您需要通过USB及PC上的文件管理器访问文件,而不是使用DDMS或类似工具,因此您可以使用Environment.getExternalStoragePublicDirectory()方法,并将Environment.DIRECTORY_DOWNLOADS作为参数传递(请注意,我不确定是否有相应的内部存储等效方法):

String baseFolder;
// check if external storage is available
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
    baseFolder = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
}
// revert to using internal storage (not sure if there's an equivalent to the above)
else {
    baseFolder = context.getFilesDir().getAbsolutePath();
}

String string = "hello world!";
File file = new File(basefolder + File.separator + "test.txt");
file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file);
fos.write(string.getBytes());
fos.flush();
fos.close();

1
好的,这很好知道。我会阅读文档并尝试理解你的代码。 - afkiwers
我在LogCat中得到了以下内容: 06-10 13:19:37.647: E/AndroidRuntime(25405): FATAL EXCEPTION: main 06-10 13:19:37.647: E/AndroidRuntime(25405): Caused by: java.lang.IllegalArgumentException: File /storage/emulated/0/Android/data/de.scuido.hddeasypull/filestest.txt 包含路径分隔符。 如何使用给定的baseFolder将文件保存到另一个位置?我不明白我必须使用什么样的路径。 - afkiwers
啊,抱歉。我忘记你使用了 openFileOutput()。请查看我的更新答案,我创建了一个文件并将其传递给 FileOutputStream()。 - britzl
启动应用程序后,我无法通过USB找到“/storage/emulated/0/Android/data/de.scuido.hddeasypull/files/test.txt”。也没有新的文件夹。 - afkiwers
奇怪,好的,有三件事可以尝试:1)调用file.getParentFile().mkdirs()以确保所有文件夹都被创建。2)在关闭流之前调用fos.flush()。3)更改为new File(basefolder + File.separator + "test.txt)。 - britzl
显示剩余4条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接