I am trying to create a new directory and a file within 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");
}
}
}
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.
Do this in order to create a new directory inside your project, create a file and then write on it:
public static void main(String[] args) {
//System.getProperty returns absolute path
File f = new File(System.getProperty("user.dir")+"/folder/file.txt");
if(!f.getParentFile().exists()){
f.getParentFile().mkdirs();
}
//Remove if clause if you want to overwrite file
if(!f.exists()){
try {
f.createNewFile();
} catch (Exception e) {
e.printStackTrace();
}
}
try {
//dir will change directory and specifies file name for writer
File dir = new File(f.getParentFile(), f.getName());
PrintWriter writer = new PrintWriter(dir);
writer.print("writing anything...");
writer.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With