开发者

Method in Java to create a file at a location, creating directories if necessary?

开发者 https://www.devze.com 2022-12-11 13:34 出处:网络
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 pat

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 th开发者_C百科ere 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.


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


Since the question also mentioned the library Apache Common IO, I report in the following a solution that uses this nice library:

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

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


Guava also has Files.createParentDirs(File).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号