【问题标题】:Using Apple's Jar Bundler on a .jar that accesses files在访问文件的 .jar 上使用 Apple 的 Jar Bundler
【发布时间】:2012-04-21 22:11:56
【问题描述】:

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

我正在尝试找出为什么会收到此FileNotFoundException 以及如何防止它。我的猜测是 Eclipse 正在使用它自己的类加载器或其他东西,并且在导出的 jarapp 中没有正确调用该类加载器。

SSCCE:以下代码在从 Eclipse 运行时有效,但不能从 .appjava -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 内。不,没有任何东西写入它。

标签: java file jar io


【解决方案1】:

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

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

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

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

【讨论】:

  • "packages resource" 我通常将其称为“嵌入式应用程序资源”。 (我正试图开始一个趋势。;)“当然,你必须将文件“file.txt”放在你的类的同一个包中。”我通常认为引用通过“类路径根目录的完整路径”获取资源。在这种情况下,可能类似于"/readfromfile/file.txt"。 +1 表示该资源可能无法作为 File 访问。
  • @AndrewThompson 你是对的,但我想建议一个非常简单的解决方案,但是我投票给你的评论!
  • 那么,file.txt 是否与ReadFromFile.java 位于同一目录中?这就是您所说的“在同一个课程中”的意思吗?
猜你喜欢
  • 2011-07-07
  • 2019-05-21
  • 2013-12-13
  • 1970-01-01
  • 2013-07-16
  • 2018-06-29
  • 2011-07-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多