ChatGPT解决这个技术问题 Extra ChatGPT

Create whole path automatically when writing to a new file

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?


J
Jon Skeet

Something like:

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

Why getParentFile and not just mkdirs?
Will it override the previous folder, if I am reissuing the same code with different sibling file?
@surajs1n: If the directory already exists, mkdirs will do nothing.
@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.
c
cdmihai

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

Important to keep in mind that relative paths might cause null pointer exception. Path pathToFile = Paths.get("myFile.txt"); Files.createDirectories(pathToFile.getParent());
if(!Files.exists(pathToFile.getParent())) Files.createDirectory(pathToFile.getParent()); //Test if the dir already exists to avoid error
@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.
A
Armand

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

M
Marcelo Cantos

Use File.mkdirs().


That will create a directory `C:\\user\Desktop\dir1\dir2\filename.txt`.
@MartinSchröder: Only if you keep the filename component.
B
Belle

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

Please, could you be more specific?
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.
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);
Thanks for that . Made my code much cleaner now. Link to recent javadoc : commons.apache.org/proper/commons-io/javadocs/api-2.5/org/…