Create whole path automatically when writing to a new file

user321068 picture user321068 · May 14, 2010 · Viewed 222.2k times · Source

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?

Answer

Jon Skeet picture Jon Skeet · May 14, 2010

Something like:

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