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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:24:13  来源:igfitidea点击:

Create whole path automatically when writing to a new file

javapathdirectoryfilewriter

提问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.

现在dir1dir2目前不存在。如果它们不存在,我希望 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

回答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

Use FileUtilsto handle all these headaches.

使用FileUtils来处理所有这些令人头疼的问题。

Edit: For example, use below code to write to a file, this method will 'checking and creating the parent directory if it does not exist'.

编辑:例如,使用下面的代码写入文件,此方法将“检查并创建不存在的父目录”。

openOutputStream(File file [, boolean append]) 

回答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);