user321068
user321068

Reputation:

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?

Upvotes: 284

Views: 273491

Answers (5)

kakacii
kakacii

Reputation: 740

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

Upvotes: 4

cdmihai
cdmihai

Reputation: 3028

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

Upvotes: 171

Jon Skeet
Jon Skeet

Reputation: 1500515

Something like:

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

Upvotes: 476

Armand
Armand

Reputation: 24343

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

Upvotes: 32

Marcelo Cantos
Marcelo Cantos

Reputation: 185852

Use File.mkdirs().

Upvotes: 18

Related Questions