1

我有一个大型项目,其中包含一个从文件中读取的类(我在下面附上了一个 SSCCE)。一切正常。但是,当我使用 Apple Jar Bundler 或 Eclipse 的“导出到 Mac OS X 应用程序命令”(按照这些说明)时,它不起作用,我得到一个java.io.FileNotFoundException.

我试图找出我为什么会得到这个FileNotFoundException以及如何防止它。我的猜测是 Eclipse 正在使用它自己的类加载器或其他东西,并且说类加载器没有在导出中正确调用,jar因此app.

SSCCE:以下代码在从 Eclipse 运行时有效,但不能从.app,java -jar甚至从目录java readfromfile.ReadFromFile执行bin

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
4

1 回答 1

3

当您创建 Jar Bundle 时,src/...路径可能不存在。

为什么不将文件作为包资源并阅读它:

Reader r = new InputStreamReader(ReadFromFile.class.getResourceAsStream("file.txt"));
BufferedReader br = new BufferedReader(r);

自然,您必须将文件“file.txt”放在您班级的同一个包中。

于 2012-04-09T14:43:19.050 回答