简体   繁体   English

Java-创建文件和目录

[英]Java - create file and dir

Assume final String fname = "/dir1/dir2/fname.ext" . 假定final String fname = "/dir1/dir2/fname.ext" I do not wish to parse the string recursively in order to create the directories if they do not exist, and only then write to a file. 我不希望递归地解析字符串以创建目录(如果目录不存在),然后仅将其写入文件。 I wish to use the given string, fname , for creating the directories and file if each of which does not exist. 如果每个目录都不存在,我希望使用给定的字符串fname创建目录和文件。

This is the code you are looking for: 这是您要查找的代码:

File myFile = new File("/dir1/dir2/fname.ext");
myFile.getParentFile().mkdirs();
// do your writing being sure the parent directories exist.

You can use mkdirs to create the path. 您可以使用mkdirs创建路径。

File f = new File("/dir1/dir2/fname.ext");
f.getParentFile().mkdirs();

And then work on the file itself. 然后处理文件本身。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM