Using java to create a new directory and file inside it

I am trying to create a new directory and a file in this directory, can someone tell me where I am going wrong?

I am using Windows and want the directory to be present in the folder where my .java file is located.

 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"); } } } 
+7
java file directory
source share
2 answers

Basically, what happens is that you create a directory called Library\test.txt , and then try to create a new file called the same, this obviously won't 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 exception if it fails, which is pretty annoying, so instead I would do something more similar ...

 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 know what the problem is ...

Additional

Creating a directory (in this context) will be in the place where you ran the program from ...

For example, you run a program from C:\MyAwesomJavaProjects\FileTest , the Library directory will be created in this directory (i.e. C:\MyAwesomJavaProjects\FileTest\Library ). Creating it in the same place as your .java file is usually not a good idea, since your application can subsequently be added to the Jar.

+22
source share

Do this 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(); } } 
+3
source share

All Articles