有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java openFileOutput:如何在/data/data…外部创建文件。。。。路径

我想知道你是否能帮我解决这个问题。我不明白如何访问“下载”文件夹或我自己的一些文件夹

我想创建一些txt文件,并通过USB访问它。我没有找到与我的问题相关的主题,因为我不知道我要搜索的确切位置

        String string = "hello world!";

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

谢谢你的提示:)


共 (1) 个答案

  1. # 1 楼答案

    从读the official documentation on file storage options开始。请记住,外部存储并不等同于“可移动SD卡”。它可以是32Gb或Nexus设备上的任何内存

    下面是一个如何获取文件目录基本文件夹的示例(即卸载应用程序时删除的文件夹,而不是卸载后仍然存在的缓存目录):

    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();