当我尝试在代码中加载 .txt 文件时,出现此错误:
java.io.FileNotFoundException: file:\C:\Users\Me\Desktop\Program.jar!\test\foo.txt (The filename, directory name, or volume label syntax is incorrect)
我加载这些文件的代码是这样的:
try {
String path = getClass().getResource(file).getPath();
BufferedReader reader = new BufferedReader(new FileReader(path));
...
} catch(IOException e) {
System.err.println("Could not read file!");
e.printStackTrace();
System.exit(-1);
}
我加载到方法中的字符串是这样的:
foo.txt
尽管我检查了很多次,该文件确实存在于该路径中,但我的程序仍然找不到它。还有为什么Program.jar的末尾有一个感叹号呢?重要吗?
感谢所有帮助回答我问题的人。
最佳答案
如果您在控制台中从 jar 中启动它,您最好以 InputStream
的形式访问您的资源并以所需的方式处理它。当您输入实际路径(尤其是非相对路径)时 - 您试图访问 jar 内的文件,这是错误的。
这是解决您的问题的接近(伪)代码:
InputStream resource = ClassName.class.getResourceAsStream("/test/foo.txt");
BufferedReader reader = new BufferedReader(new InputStreamReader(resource));
//do some stuff
resource.close();
reader.close();
感叹号是 JVM 用于标记路径中的 .jar
文件的分隔符。
关于Java - 在 .jar 中使用 .txt 文件时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31208507/