views:

115

answers:

1

I am attempting to write a file using java.io, where I am trying to create it at the location "some/path/to/somewhere/then-my-file". When the file is being created, any of the directories on the path may or may not exist. Rather than throw an IOException because there are no such directories, I would like the directories to be created transparently, as and when required.

Is there a method that will create any directories required on the way to writing a file? I am looking for something within the Java SDK, or within a lightweight library I can add to the classpath, e.g. Apache Commons IO.

P.S. For clarity's sake, I have already coded a solution, which works for the fairly narrow way I'm testing it, so I don't really need suggestions on how to write the method I'm looking for. I'm looking for a method which will have been fairly well tested, and cross-platform.

+14  A: 

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

skaffman
+1. You're too fast
ChssPly76
sorry... my keyboard's on fire now... can't .... type...
skaffman
Awesome, thanks.
Grundlefleck
Note that mkdirs() doesn't throw an IOException if it can't create the directories, it just returns false. It's a good idea to check that the directory already exists, or was created successfully. If (!directory.exists()
Sam Barnum
Yup, fair point. You can get into some fairly unpleasant logic there, such as the parent existing but not being a directory, or existing and not being writeable, etc.
skaffman