WannaBeCoder WannaBeCoder - 3 months ago 7
Java Question

using java to create a new directory and a file within it

i am trying to create a new directory and a file with in this directory,can any one tell me where am i going wrong.
i am using a windows system and i want the directory to be present in the folder my .JAVA file is present.

import java.io.*;
class PS_Task1
{
public static void main(String[] args)
{
try
{
File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();
}
catch(Exception e)
{
System.out.println("ecception");
}


}
}

Answer

Basically, what's happening is, you are creating a directory called Library\test.txt, then trying to create a new file called the same thing, this obviously isn't going to work.

So, instead of...

File file = new File("Library\\test.txt");
file.mkdir();
file.createNewFile();

Try...

File file = new File("Library\\test.txt");
file.getParentFile().mkdir();
file.createNewFile();

Additional

mkdir will not actually throw any kind of exception if it fails, which is rather annoying, so instead, I would do something more like...

File file = new File("Library\\test.txt");
if (file.getParentFile().mkdir()) {
    file.createNewFile();
} else {
    throw new IOException("Failed to create directory " + file.getParent());
}

Just so I knew what the actual problem was...

Additional

The creation of the directory (in this context) will be at the location you ran the program from...

For example, you run the program from C:\MyAwesomJavaProjects\FileTest, the Library directory will be created in this directory (ie C:\MyAwesomJavaProjects\FileTest\Library). Getting it created in the same location as your .java file is generally not a good idea, as your application may actually be bundled into a Jar later on.