Java won't let me createNewFile because the file I want to create doesn't exist, which, duh, that's why I want to create it. Here's my code snippet.
System.out.println("Please input the path of the install directory.");
System.out.print(">");
installLocation = input.nextLine();
File spreadsheet = new File (installLocation + "diatracker.csv");
File settingsFile = new File (installLocation + "settings.txt");
if ( spreadsheet.exists() )
{
if ( isValidFile ( spreadsheet.toString() ) )
{
//do nothing
}
else
{
spreadsheet.delete();
spreadsheet.createNewFile();
}
}
else
{
spreadsheet.createNewFile();
}
And here is my error.
Please input the path of the install directory.
C:\Users\DigiDuncan\Desktop\DiaTracker\
Exception in thread "main" java.io.IOException: The system cannot find the path specified
at java.io.WinNTFileSystem.createFileExclusively(Native Method)
at java.io.File.createNewFile(Unknown Source)
at DiaTrackApp.firstTimeSetup(DiaTrackApp.java:201)
at DiaTrackApp.main(DiaTrackApp.java:50)
Please help me out, this program is really important to me. Thanks!
I literally just named the folder wrong, didn't I. Sorry for wasting your time, guys. .~.
This is most probably caused because the given parent folder path does not exist. A simple way of fixing this would be to use:
file.getParentFile().mkdirs();
File#mkdirs()
will essentially create all parent folders to the file if they do not exist, and also consider the given file as a new folder. This is why you should use getParentFile().mkdirs();
if you want to still create a new file with the last part of the path being well, a file!
Edit: Just an extra note, the good side of using getParentFile()
is so you do not have to worry about the file path being changed or incorrect at runtime.
You should also use input.nextLine().replace("/", File.separator).replace("\\", File.separator);
in case the user input does not follow the OS's path guidelines.