Create whole path automatically when writing to a

2019-01-10 00:22发布

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?

5条回答
一纸荒年 Trace。
2楼-- · 2019-01-10 00:51

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);
查看更多
倾城 Initia
3楼-- · 2019-01-10 00:53

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);
查看更多
倾城 Initia
4楼-- · 2019-01-10 00:56

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]) 
查看更多
做自己的国王
5楼-- · 2019-01-10 00:59

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
查看更多
一夜七次
6楼-- · 2019-01-10 01:06
登录 后发表回答