Reputation: 641
I'm trying to create an empty .properties file on my filesystem using java.io.File.
My code is:
File newFile = new File(new File(".").getAbsolutePath() + "folder\\" + newFileName.getText() + ".properties");
if (newFile.createNewFile()){
//do sth...
}
It says that it's impossible to find the specified path. Printing the Files's constructor's argument it shows correctly the absolute path.
What's wrong?
Upvotes: 0
Views: 3001
Reputation: 641
Trivially I missed that new File(".").getAbsolutePath()
returns the project's absolute path with the .
at the end so my folder
whould be called as .folder
. Next time I'll check twice.
Upvotes: 0
Reputation: 347204
new File("folder", newFileName.getText() + ".properties")
which will create a file reference to the specified file in the folder
directory relative to the current working directorycreateNewFile
, as it won't do this for youFor example...
File newFile = new File("folder", newFileName.getText() + ".properties");
File parentFile = newFile.getParentFile();
if (parentFile.exists() || parentFile.mkdirs()) {
if (!newFile.exists()) {
if (newFile.createNewFile()){
//do sth...
} else {
throw new IOException("Could not create " + newFile + ", you may not have write permissions or the file is opened by another process");
}
}
} else {
throw new IOException("Could not create directory " + parentFile + ", you may not have write permissions");
}
Upvotes: 2
Reputation: 455
I think the "." operator might be causing the error not sure what you are trying to do there, may have misunderstood your intentions but try this instead:
File newFile = new File(new File("folder\\").getAbsolutePath() + ".properties");
Upvotes: 1