Java JAR找不到文件 [英] Java JAR can't find file
问题描述
我在eclipse中运行一个引用程序源文件夹中的文件的程序。但是,当我将程序导出到可运行的JAR时,程序似乎无法找到该文件。从本质上讲,这个程序在eclipse中运行得很完美,但是当它是一个独立的程序时它不会这样做。
I am running a program in eclipse that references a file in the program's source folder. However, when I export the program into a runnable JAR, the program cannot seem to find the file. Essentially, the program works perfect in eclipse but doesn't do so when it's a standalone program.
我附上了一张照片,说明我如何在程序中引用该文件。
I've attached a photo of how I reference the file in the program.
推荐答案
一旦它在jar中,你就无法使用 new File()
- 它现在是一个类路径资源。你需要使用 this.getClass()。getResourceAsStream(/ TestFileFolder / TRANSFER.xls);
(或者,如果你的方法是静态的,你需要使用 className.class
代替 getClass()
)。
Once it's in the jar, you can't find it using new File()
-- it's now a class path resource. You need to use this.getClass().getResourceAsStream("/TestFileFolder/TRANSFER.xls");
(or, if your method is static, you need to use the className.class
in place of getClass()
).
这实际上是一个功能 - 如果由于任何原因你需要更改 TRANSFER.xls
资源,你可以通过在类路径中隐藏它而不重新打包jar来实现。
this is actually a feature -- if for any reason you need to change the TRANSFER.xls
resource, you can do so by shadowing it in the classpath without repacking the jar.
这篇关于Java JAR找不到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!