How to create a file in a directory in java?

Uerefer picture Uerefer · May 26, 2011 · Viewed 378.2k times · Source

If I want to create a file in C:/a/b/test.txt, can I do something like:

File f = new File("C:/a/b/test.txt");

Also, I want to use FileOutputStream to create the file. So how would I do it? For some reason the file doesn't get created in the right directory.

Answer

RMT picture RMT · May 26, 2011

The best way to do it is:

String path = "C:" + File.separator + "hello" + File.separator + "hi.txt";
// Use relative path for Unix systems
File f = new File(path);

f.getParentFile().mkdirs(); 
f.createNewFile();