【问题标题】:How to create a file -- including folders -- for a given path?如何为给定路径创建文件(包括文件夹)?
【发布时间】:2011-05-01 17:39:50
【问题描述】:

我正在从网上下载一个 zip 文件。它包含文件夹和文件。使用ZipInputstreamZipEntry 解压缩它们。 Zipentry.getName 将文件名指定为 htm/css/aaa.htm

所以我正在创建新的File(zipentry.getName);

但问题是抛出异常:File not found。我知道它正在创建子文件夹htmcss

我的问题是:如何通过上面的路径创建一个包含其子目录的文件?

【问题讨论】:

    标签: java android file


    【解决方案1】:

    使用这个:

    File targetFile = new File("foo/bar/phleem.css");
    File parent = targetFile.getParentFile();
    if (parent != null && !parent.exists() && !parent.mkdirs()) {
        throw new IllegalStateException("Couldn't create dir: " + parent);
    }
    

    虽然您可以在不检查结果的情况下直接执行file.getParentFile().mkdirs(),但最好的做法是检查操作的返回值。因此,首先检查现有目录,然后检查是否成功创建(如果它尚不存在)。

    此外,如果路径不包含任何父目录,parent 将是 null。检查它的稳健性。

    参考:

    【讨论】:

    • 如果我有 a/b/c/d/e.txt。创建 e.txt。我必须创建 a、b、、c、d 文件夹。我怎样才能得到它?
    • mkDir() 只创建一级父母,mkDirs() 创建所有父母、祖父母等。
    • 正如我所写:new File("a/b/c/d/e.txt").getParentFile().mkDirs() 创建所有需要的文件夹,而不仅仅是父文件夹
    • 应该是mkdirs 而不是mkDirs。小“d”。
    • 改变了这一点。所以习惯使用自动补全。
    【解决方案2】:

    如果需要,您需要创建子目录,因为您循环浏览 zip 文件中的条目。

    ZipFile zipFile = new ZipFile(myZipFile);
    Enumeration e = zipFile.entries();
    while(e.hasMoreElements()){
        ZipEntry entry = (ZipEntry)e.nextElement();
        File destinationFilePath = new File(entry.getName());
        destinationFilePath.getParentFile().mkdirs();
        if(!entry.isDirectory()){
            //code to uncompress the file 
        }
    }
    

    【讨论】:

    • 看起来不错,但我会在 if(!entry.isDirectory()) 块内创建文件夹,因为无论如何您都在创建所有必需的父文件夹,所以当条目是目录时不需要这样做。
    【解决方案3】:

    您可以使用 Google 的 库通过 Files 类在几行中完成:

    Files.createParentDirs(file);
    Files.touch(file);
    

    https://code.google.com/p/guava-libraries/

    【讨论】:

      【解决方案4】:

      查看您在File 对象上使用.mkdirs() 方法的文件:http://www.roseindia.net/java/beginners/java-create-directory.shtml

      isDirectoryCreated = (new File("../path_for_Directory/Directory_Name")).mkdirs(); 如果(!isDirectoryCreated) { // 创建目录失败 }

      【讨论】:

        【解决方案5】:

        我就是这样做的

        static void ensureFoldersExist(File folder) {
            if (!folder.exists()) {
                if (!folder.mkdirs()) {
                    ensureFoldersExist(folder.getParentFile());
                }
            }
        }
        

        【讨论】:

          【解决方案6】:

          Java NIO API Files.createDirectories

          import java.nio.file.Files;
          import java.nio.file.Path;
          import java.nio.file.Paths;
          
          Path path = Paths.get("/folder1/folder2/folder3");
          Files.createDirectories(path);
          
          

          【讨论】:

            猜你喜欢
            • 2015-01-25
            • 1970-01-01
            • 2019-05-17
            • 2017-08-06
            • 1970-01-01
            • 1970-01-01
            • 2021-09-05
            • 1970-01-01
            相关资源
            最近更新 更多