简体   繁体   English

找不到指定的Java文件

[英]Cannot find the file specified java

我试图打开一个位于我的netbeans项目文件夹中的txt文件,但是它说系统找不到指定的文件。

 File file = new File("Knowledge Base.txt");

When running on IDEs, the current directory is not always the directory where you place your .class file. 在IDE上运行时,当前目录并非始终是您放置.class文件的目录。

Find out the current directory using 使用以下命令查找当前目录

System.getProperty("user.dir")

And then make necessary changes to the path to get it to your directory. 然后对路径进行必要的更改以使其进入目录。

The path given assumes an absolute path, so by not prefixing it it will assume it is in the root directory. 给定的路径假定为绝对路径,因此不加前缀就将假定它位于根目录中。 To fix this, you can do this: 要解决此问题,您可以执行以下操作:

String path = new File(".").getAbsolutePath();
path=path.substring(0, path.length() - 1);
path+="Knowledge Base.txt"
File file = new File(path);

The first line gets the absolute path of the app file. 第一行获取应用程序文件的绝对路径。 The second subtracts the last character, leaving a / character for the directory. 第二个减去最后一个字符,为目录保留一个/字符。 The third line adds your file to the string, and the fourth constructs a file object from the string. 第三行将文件添加到字符串,第四行从字符串构造文件对象。 This method assumes that the file is located in the same folder as your class. 此方法假定文件与您的课程位于同一文件夹中。

If your program is packaged as a .jar along with a libs folder, then you can do this instead. 如果您的程序与libs文件夹一起打包为.jar,则可以执行此操作。

String path = Test.class.getProtectionDomain().getCodeSource().getLocation().getPath();
String decodedPath = URLDecoder.decode(path, "UTF-8");
decodedPath+="/Temp";
File file = new File(decodedPath);

This time we're getting the path to the .jar, then decoding it with UTF-8 because spaces would become "%20" if we didn't. 这次我们获取到.jar的路径,然后使用UTF-8对其进行解码,因为如果不这样做,空格将变为“%20”。 You would need to replace "Test" with the name of your class, and "/Temp" with the path inside the .jar to the file. 您需要用类名替换“ Test”,并用.jar到文件的路径替换“ / Temp”。 The rest is the same as the non .jar method, but we don't need to remove "." 其余与非.jar方法相同,但是我们不需要删除“。” from the end of the string. 从字符串的末尾开始。 Uses this Answer by Fab to decode the filepath for the .jar file. Fab使用 Answer来解码.jar文件的文件路径。

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

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