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?
Since Java 1.7 you can use Files.createFile:
Use
File.mkdirs()
: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'.
Something like:
Use
File.mkdirs()
.