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

Scu*_*ido 2 java android

我想知道你是否可以帮我解决这个问题.我不明白我如何访问例如"下载"文件夹或我自己的一些文件夹.

我想创建一些txt文件,并通过USB访问它.我没有找到与我的问题相关的话题,因为我不知道我在哪里搜索.

        String string = "hello world!";

        FileOutputStream fos = openFileOutput("test.txt", Context.MODE_PRIVATE);
        fos.write(string.getBytes());
        fos.close();
Run Code Online (Sandbox Code Playgroud)

谢谢提示:)

bri*_*tzl 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();
Run Code Online (Sandbox Code Playgroud)

更新:由于您需要通过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();
Run Code Online (Sandbox Code Playgroud)