Create whole path automatically when writing to a new file

余生颓废 提交于 2019-11-26 11:48:14

问题


I want to write a new file with the FileWriter. I use it like this:

FileWriter newJsp = new FileWriter(\"C:\\\\user\\Desktop\\dir1\\dir2\\filename.txt\");

Now dir1 and dir2 currently 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.

How can I achieve this?


回答1:


Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);



回答2:


Since Java 1.7 you can use Files.createFile:

Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);



回答3:


Use 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);



回答4:


Use File.mkdirs().




回答5:


Use FileUtils to handle all these headaches.

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]) 


来源:https://stackoverflow.com/questions/2833853/create-whole-path-automatically-when-writing-to-a-new-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!