Andrea Grimandi
Andrea Grimandi

Reputation: 641

Creating file on filesystem with java.io.File

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

Answers (3)

Andrea Grimandi
Andrea Grimandi

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

MadProgrammer
MadProgrammer

Reputation: 347204

  1. You can use 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 directory
  2. You should make sure that the directory exists before calling createNewFile, as it won't do this for you

For 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

Manish Mallavarapu
Manish Mallavarapu

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

Related Questions