javaandroidfile

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


Am downloading a zip file from web. It contain folders and files. Uncompressing them using ZipInputstream and ZipEntry. Zipentry.getName gives the name of file as htm/css/aaa.htm.

So I am creating new File(zipentry.getName);

But problem it is throwing an exception: File not found. I got that it is creating subfolders htm and css.

My question is: how to create a file including its sub directories, by passing above path?


Solution

  • Use this:

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

    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).

    Also, if the path doesn't include any parent directory, parent would be null. Check it for robustness.

    Reference: