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

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:

  • File.getParentFile()
  • File.exists()
  • File.mkdir()
  • File.mkdirs()

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/