How to create a file — including folders — for a given path?

后端 未结 5 1273
旧时难觅i
旧时难觅i 2021-02-04 23:27

Am downloading a zip file from web. It contain folders and files. Uncompressing them using ZipInputstream and ZipEntry. Zipentry.getName

相关标签:
5条回答
  • 2021-02-05 00:05

    You need to create subdirectories if necessary, as you loop through the entries in the zip file.

    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 
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:07

    You can use Google's guava library to do it in a couple of lines with Files class:

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

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

    0 讨论(0)
  • 2021-02-05 00:07

    Looks at the file you use the .mkdirs() method on a File object: http://www.roseindia.net/java/beginners/java-create-directory.shtml

            isDirectoryCreated = (new File("../path_for_Directory/Directory_Name")).mkdirs();
            if (!isDirectoryCreated) 
            {
                // Directory creation failed
            }
    

    0 讨论(0)
  • 2021-02-05 00:18

    This is how I do it

    static void ensureFoldersExist(File folder) {
        if (!folder.exists()) {
            if (!folder.mkdirs()) {
                ensureFoldersExist(folder.getParentFile());
            }
        }
    }
    
    0 讨论(0)
  • 2021-02-05 00:23

    Use this:

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

    While you can just do file.getParentFile().mkdirs() without checking the result, it's considered a best practice to check for the return value of the operation. Hence the check for an existing directory first and then the check for successful creation (if it didn't exist yet).

    Reference:

    • File.getParentFile()
    • File.exists()
    • File.mkdir()
    • File.mkdirs()
    0 讨论(0)
提交回复
热议问题