【问题标题】:Error reading file in a jar读取 jar 中的文件时出错
【发布时间】:2017-11-28 17:02:50
【问题描述】:

我正在尝试在 java 中读取文件,当我通过 IDE 运行程序时它工作正常,但是当我执行 jar 时它试图打开它时,它说该文件不存在。这是失败的代码。

    public class Main {

    public static void main(String[] args) {

            try {
                App app = new App("files/" + "jsonFile.json", printWriter);
                app.runApp();

            } catch (Exception e) {
                logger.error("error", e);
            }
    }   
}




public class App {

public void runApp(){
    File fileDescription = new File("./" + pathDescription);
    StringBuilder allDescription = new StringBuilder();
    try {
            FileReader fr = new FileReader(fileDescription);
            BufferedReader br = new BufferedReader(fr);
            String line = "";
            while ((line = br.readLine()) != null) {
                allDescription.append(line);
            }
            JSONDescription = allDescription.toString();
            fr.close();
            br.close();
    } catch (IOException e) {
            logger.error("Error reading file",e);
    }
}

}

我知道该文件存在于 jar 中,因为我使用 jarzilla 手动查看了 jar。不知道会发生什么。

【问题讨论】:

  • 你的代码块不是你直接在 App 里面写的业务逻辑,里面没有任何方法,变量 pathDescription 取什么值。
  • 这不可能是代码。 new app("files/" + "jsonFile.json", printWriter) 将无法编译,因为 app 以小写字母开头 + 您的类没有采用 String 和 printWriter 的构造函数。由于您没有定义任何 printWriter,因此 main 也不会编译。
  • 这不是 C,你的 main 方法必须在一个类中。

标签: java


【解决方案1】:

您可以使用以下方式在 jar 中查找文件:

    InputStream stream = ClassInsideTheJar.class.getResourceAsStream("/files/jsonFile.json");
    BufferedReader br  = new BufferedReader(new InputStreamReader(stream));

其中“ClassInsideTheJar”是 jar 中的任何类。

【讨论】:

    【解决方案2】:

    要访问 JAR 中的文件,您可以使用类似

    BufferedReader reader = new BufferedReader(new InputStreamReader(
    this.getClass().getResourceAsStream("files/jsonFile.json")));
    

    这假设在你的 jar 的根目录中有一个名为 files 的文件夹,并且在里面你有 jsonFile.json 文件。

    【讨论】:

    • 这种方式可以读取文件,但是无法获取到文件的路径。
    【解决方案3】:

    当您在 IDE 中运行程序时,编译后的代码存在于 jar 之外的文件系统中。 IDE 编译代码,然后运行程序,而不构建 JAR 文件。因此,您的程序找到了该文件,因为该文件仍然存在于文件系统中。

    要在 JAR 中打开文件,您需要使用另一个 API:将文件作为资源加载。

    load file within a jar

    【讨论】:

      猜你喜欢
      • 2013-04-15
      • 2018-02-17
      • 2016-07-10
      • 2020-12-16
      • 1970-01-01
      • 2018-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多