Create whole path automatically when writing to a new file

JavaPathDirectoryFilewriter

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Something like:

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

Solution 2 - Java

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

Solution 3 - Java

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

Solution 4 - Java

Solution 5 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser321068View Question on Stackoverflow
Solution 1 - JavaJon SkeetView Answer on Stackoverflow
Solution 2 - JavacdmihaiView Answer on Stackoverflow
Solution 3 - JavaArmandView Answer on Stackoverflow
Solution 4 - JavaMarcelo CantosView Answer on Stackoverflow
Solution 5 - JavakakaciiView Answer on Stackoverflow