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.
Madprogrammer
source share