Method in Java to create a file in place by creating directories if necessary?

I am trying to write a file using java.io where I am trying to create it in the location "some/path/to/somewhere/then-my-file" . When a file is created, any of the directories in the path may or may not exist. Instead of throwing an IOException because there are no such directories, I would like directories to be created transparently when and when necessary.

Is there a method that will create any directories needed to write a file? I am looking for something in the Java SDK or within an easy library that I can add to the classpath, for example. Apache Commons IO.

PS For clarity, I have already coded a solution that works in a rather narrow way, I am testing it, so I do not need suggestions on how to write the method I'm looking for. I am looking for a method that will be fairly well tested and cross-platform.

+6
source share
3 answers

new File("some/path/to/somewhere/then-my-file").getParentFile().mkdirs()

+24
source

Since the question also mentioned the Apache Common IO library, I am reporting in the following a solution that uses this beautiful library:

 File file = new File("... the directory path ..."); FileUtils.forceMkdir(file); 

This solution uses the FileUtils class, from the package org.apache.commons.io and the forceMkdir method, which "Makes a directory, including any necessary, but nonexistent parent directories."

+2
source
+2
source

All Articles