【发布时间】:2012-04-21 22:11:56
【问题描述】:
我有一个大型项目,其中包含一个从文件中读取的类(我在下面附上了一个 SSCCE)。一切正常。但是,当我使用 Apple Jar Bundler 或 Eclipse 的“导出到 Mac OS X 应用程序命令”(在 these instructions 之后)时,它不起作用,我得到了 java.io.FileNotFoundException。
我正在尝试找出为什么会收到此FileNotFoundException 以及如何防止它。我的猜测是 Eclipse 正在使用它自己的类加载器或其他东西,并且在导出的 jar 和 app 中没有正确调用该类加载器。
SSCCE:以下代码在从 Eclipse 运行时有效,但不能从 .app、java -jar 甚至从 bin 目录执行的 java readfromfile.ReadFromFile 运行。
在ReadFromFile.java中:
package readfromfile;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import javax.swing.BoxLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class ReadFromFile {
public static void main(String[] args) {
String filepath = "src/readfromfile/file.txt";
try {
BufferedReader br = new BufferedReader(new FileReader(filepath));
JFrame frame = new JFrame();
frame.getContentPane().setLayout(
new BoxLayout(frame.getContentPane(), BoxLayout.Y_AXIS));
for (String line; (line = br.readLine()) != null;) {
frame.getContentPane().add(new JLabel(line));
}
frame.pack();
frame.setVisible(true);
} catch (FileNotFoundException e) {
System.err.println("File not found");
e.printStackTrace();
} catch (IOException e) {
System.err.println("IOexception");
e.printStackTrace();
}
}
}
在file.txt中:
I am text
【问题讨论】:
-
“访问文件的 .jar” 资源是否包含在 inside Jar 中?如果是这样,
File不能用于访问它,而是使用URL。 -
顺便说一句 - 如果读取 & 写入需要资源,请参阅How can a Java program use files inside the .jar for read and write?
-
@AndrewThompson:是的,它位于
.jar内。不,没有任何东西写入它。