Create whole path automatically when writing to a new file
Asked Answered
S

5

284

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?

Schecter answered 14/5, 2010 at 11:50 Comment(0)
C
476

Something like:

File file = new File("C:\\user\\Desktop\\dir1\\dir2\\filename.txt");
file.getParentFile().mkdirs();
FileWriter writer = new FileWriter(file);
Calbert answered 14/5, 2010 at 11:53 Comment(6)
Why getParentFile and not just mkdirs?Snyder
Will it override the previous folder, if I am reissuing the same code with different sibling file?Felder
@surajs1n: If the directory already exists, mkdirs will do nothing.Calbert
@sauperl: If the file doesn't exist yet, mkdirs() will assume everything specified is a directory and creates it as such (just tested it). By using getParentFile(), you leave the creation of the file itself to the FileWriter.Vittle
Do we need to check if getParentFile() returns null, for example if the file is directly in the root directory?Martinemartineau
@Cloud: Not for the specific code I've given, which clearly isn't in the root directory. As with all SO answers, you should consider your own context and how you may need to change the code.Calbert
L
173

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);
Litigable answered 18/10, 2013 at 21:43 Comment(3)
Important to keep in mind that relative paths might cause null pointer exception. Path pathToFile = Paths.get("myFile.txt"); Files.createDirectories(pathToFile.getParent());Daberath
if(!Files.exists(pathToFile.getParent())) Files.createDirectory(pathToFile.getParent()); //Test if the dir already exists to avoid errorCollywobbles
@AndreNel JavaDoc of createDirectories states: Unlike the createDirectory method, an exception is not thrown if the directory could not be created because it already exists.Reservist
V
32

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);
Villagomez answered 14/5, 2010 at 11:53 Comment(0)
D
18

Use File.mkdirs().

Dentate answered 14/5, 2010 at 11:53 Comment(2)
That will create a directory `C:\\user\Desktop\dir1\dir2\filename.txt`.Cresa
@MartinSchröder: Only if you keep the filename component.Dentate
O
4

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]) 
Outplay answered 11/4, 2013 at 9:23 Comment(4)
Please, could you be more specific?Endorsed
Hi Jean, Edited. There is a whole bunch of other useful methods under FileUtils. Apache Commons IO classes such as OIUtils and FileUtils makes java developers' life easier.Outplay
I agree FileUtils is a good way to go, but I think an easier way to this is using writeStringToFile, not openOutputStream. E.g. File file = new File("C:/user/Desktop/dir1/dir2/filename.txt"); FileUtils.writeStringToFile(file,"foo bar baz",true);Abe
Thanks for that . Made my code much cleaner now. Link to recent javadoc : commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…Parsec

© 2022 - 2024 — McMap. All rights reserved.