简体   繁体   English

Java文件IO +相对路径+ NetBeans

[英]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 ? 为什么file.createNewFile()给我一个IOException消息,提示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? 在NetBeans外部运行此代码似乎可以正常工作,NetBeans是否可以处理相对文件链接?

Thanks in advance for any help! 在此先感谢您的帮助!

If ./data does not exist, that call will fail. 如果./data不存在,则该调用将失败。

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();

Netbeans is running the java program from the dist folder. Netbeans从dist文件夹运行Java程序。 You would need to create the data folder in there. 您将需要在其中创建data文件夹。 However, I believe in some cases, Netbeans will clean out the entire folder and therefore delete it. 但是,我相信在某些情况下,Netbeans会清理整个文件夹并因此将其删除。 I would use an absolute path. 我会使用绝对路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM