【问题标题】:Android create folders in Internal memory issueAndroid在内部存储器问题中创建文件夹
【发布时间】:2011-12-29 11:38:06
【问题描述】:

我在为我的应用程序在内部存储器中创建文件夹时遇到了一点问题。我正在使用这段代码:

    public static void createFoldersInInternalStorage(Context context){
    try {

        File usersFolder = context.getDir("users", Context.MODE_PRIVATE);
        File fileWithinMyDir = new File(usersFolder, "users.txt"); //Getting a file within the dir.
        FileOutputStream out = new FileOutputStream(fileWithinMyDir); //Use the stream as usual to write into the file.

        File dataFolder = context.getDir("data", Context.MODE_PRIVATE);
        File fileWithinMyDir2 = new File(dataFolder, "data.txt"); //Getting a file within the dir.
        FileOutputStream out2 = new FileOutputStream(fileWithinMyDir2); //Use the stream as usual to write into the file.

        File publicFolder = context.getDir("public", Context.MODE_PRIVATE);
        File fileWithinMyDir3 = new File(publicFolder, "public.txt"); //Getting a file within the dir.
        FileOutputStream out3 = new FileOutputStream(fileWithinMyDir3); //Use the stream as usual to write into the file.

    } catch(FileNotFoundException e){
        e.printStackTrace();
    }
}

因此创建了文件夹,但在其名称前面有开头 "app_"app_usersapp_dataapp_public。有没有办法用我给的名字创建文件夹?还有一个问题:我想首先创建文件夹Documents,然后在上面创建所有其他文件夹"Data, Public, Users"....最后一个问题:如果我想在@987654328 中创建文件,如何提供正确的文件夹路径@ 在内存中?

提前致谢!

【问题讨论】:

    标签: android memory internal


    【解决方案1】:

    你可以用这个:

    File myDir = context.getFilesDir();
    String filename = "documents/users/userId/imagename.png";
    File file = new File(myDir, filename);
    file.createNewFile();
    file.mkdirs();
    FileOutputStream fos = new FileOutputStream(file);
    fos.write(mediaCardBuffer);
    fos.flush();
    fos.close();
    

    【讨论】:

      【解决方案2】:

      有没有办法用我给的名字创建文件夹?

      使用getFilesDir() 和Java 文件I/O 代替getDir()

      如果我想在内部存储器的 Documents/Users/myfile.txt 中创建文件,如何提供正确的文件夹路径?

      使用 getFilesDir() 和 Java 文件 I/O,例如采用 FileString 组合路径的 File 构造函数。

      【讨论】:

      • 我刚试过这个,它没有创建文件或文件夹:File usersFolder = context.getFilesDir(); File fileWithinMyDir = new File(usersFolder, "documents/users/users.txt"); //Getting a file within the dir. FileOutputStream out = new FileOutputStream(fileWithinMyDir); out.write("adasdasdasd".getBytes());
      • @Bombastic:当然。目录不存在。您必须创建目录。这是标准的 Java I/O,是你在学习 Java 时应该学到的。在指向您最深目录的File 对象上使用mkdirs() 以创建该点的目录树。
      • 在内存中创建文件夹时是否有深度限制?因为现在我在outputstream 之前使用上面的代码+file.mkdirs(),它把FileNotFoundExceptionoutputstream 放在一起。我要创建的路径是documents/users/userId/3456.png
      • @Bombastic:我知道mkdirs() 没有限制。同样,在 目录 上调用mkdirs()。如果你在 file 上调用它,它会创建一个带有你的文件名的目录,这意味着你不能创建一个同名的文件。见exampledepot.com/egs/java.io/CreateDir.html
      猜你喜欢
      • 2021-04-03
      • 2015-02-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多