Java 写入新文件时自动创建整个路径
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2833853/
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
Create whole path automatically when writing to a new file
提问by
I want to write a new file with the FileWriter. I use it like this:
我想用FileWriter. 我像这样使用它:
FileWriter newJsp = new FileWriter("C:\user\Desktop\dir1\dir2\filename.txt");
Now dir1and dir2currently don't exist. I want Java to create them automatically if they aren't already there. Actually Java should set up the whole file path if not already existing.
现在dir1和dir2目前不存在。如果它们不存在,我希望 Java 自动创建它们。实际上,如果不存在,Java 应该设置整个文件路径。
How can I achieve this?
我怎样才能做到这一点?
采纳答案by Jon Skeet
Something like:
就像是:
File file = new File("C:\user\Desktop\dir1\dir2\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
回答by Marcelo Cantos
Use File.mkdirs().
回答by Armand
Use File.mkdirs():
使用File.mkdirs():
File dir = new File("C:\user\Desktop\dir1\dir2");
dir.mkdirs();
File file = new File(dir, "filename.txt");
FileWriter newJsp = new FileWriter(file);
回答by kakacii
回答by cdmihai
Since Java 1.7 you can use Files.createFile:
从 Java 1.7 开始,您可以使用 Files.createFile:
Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);

