Java 如何在缺少父目录的情况下创建新文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3090761/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to create a new file together with missing parent directories?
提问by Pentium10
When using
使用时
file.createNewFile();
I get the following exception
我收到以下异常
java.io.IOException: Parent directory of file does not exist: /.../pkg/databases/mydb
I am wondering is there a createNewFile that creates the missing parent directories?
我想知道是否有 createNewFile 创建丢失的父目录?
采纳答案by Jon Skeet
Have you tried this?
你试过这个吗?
file.getParentFile().mkdirs();
file.createNewFile();
I don't know of a singlemethod call that will do this, but it's pretty easy as two statements.
我不知道的一个方法调用,将做到这一点,但它很容易,因为两个语句。
回答by Zoltán
Jon's answer works if you are certain that the path string with which you are creating a file includes parent directories, i.e. if you are certain that the path is of the form <parent-dir>/<file-name>
.
如果您确定用于创建文件的路径字符串包含父目录,即如果您确定路径的形式为<parent-dir>/<file-name>
.
If it does not, i.e. it is a relative path of the form <file-name>
, then getParentFile()
will return null
.
如果不是,即它是表单的相对路径<file-name>
,getParentFile()
则将返回null
。
E.g.
例如
File f = new File("dir/text.txt");
f.getParentFile().mkdirs(); // works fine because the path includes a parent directory.
File f = new File("text.txt");
f.getParentFile().mkdirs(); // throws NullPointerException because the parent file is unknown, i.e. `null`.
So if your file path may or may not include parent directories, you are safer with the following code:
因此,如果您的文件路径可能包含也可能不包含父目录,那么使用以下代码会更安全:
File f = new File(filename);
if (f.getParentFile() != null) {
f.getParentFile().mkdirs();
}
f.createNewFile();
回答by Ted
As of java7, you can also use NIO2 API:
从 java7 开始,您还可以使用 NIO2 API:
void createFile() throws IOException {
Path fp = Paths.get("dir1/dir2/newfile.txt");
Files.createDirectories(fp.getParent());
Files.createFile(fp);
}