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

后端 未结 5 1280
旧时难觅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: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()

提交回复
热议问题