Bill
Bill

Reputation: 2349

Java File IO + relative paths + NetBeans

Quite simply:

File account = new File("./data/account");
account.createNewFile();

Gives me:

java.io.IOException: No such file or directory
  at java.io.UnixFileSystem.createFileExclusively(Native Method)
  at java.io.File.createNewFile(File.java:900)
  ...

Why Does file.createNewFile() give me a IOException with the message No such file or directory? I'm telling it to create the file.

Running this code outside of NetBeans seems to work with no problem, can NetBeans not handle relative file links?

Thanks in advance for any help!

Upvotes: 0

Views: 2814

Answers (2)

Jeffrey
Jeffrey

Reputation: 44808

If ./data does not exist, that call will fail.

File f = new File("./data/account");
if(!f.getParentFile().exists()) { // if the directories don't exist
    if(!f.getParentFile().mkdirs()) { // if making the directories fails
        // directories weren't created, throw exception or something
    }
}
f.createNewFile();

Upvotes: 2

poy
poy

Reputation: 10507

Netbeans is running the java program from the dist folder. You would need to create the data folder in there. However, I believe in some cases, Netbeans will clean out the entire folder and therefore delete it. I would use an absolute path.

Upvotes: 1

Related Questions