简体   繁体   English

读取Jar中的文件时出错

[英]Error reading file in a jar

I'm trying to read a file in java, when I run the program through the IDE it works fine but when it tries to open it when I execute the jar it says the file does not exist. 我正在尝试用Java读取文件,当我通过IDE运行该程序时,它工作正常,但是当我执行jar时尝试打开该文件时,它说该文件不存在。 Here is the code where it fails. 这是失败的代码。

    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);
    }
}

} }

I know the file exists inside the jar because I looked manually into the jar using jarzilla. 我知道文件存在于jar中,因为我使用jarzilla手动查看了jar。 Any idea of what it could be happening. 任何可能发生的事情的想法。

To access files within the JAR, you could use something like 要访问JAR中的文件,您可以使用类似

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

This assumes that there is a folder called files in the root of your jar, and inside that you have the jsonFile.json file. 假设jar的根目录中有一个名为files的文件夹,并且在其中有jsonFile.json文件。

You can lookup a file inside a jar using something like this: 您可以使用以下方式在jar中查找文件:

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

Where "ClassInsideTheJar" is any class in the jar. 其中“ ClassInsideTheJar”是罐中的任何类。

When you run the program inside an IDE, the compiled code exists outside the jar, in the file system. 当您在IDE中运行程序时,已编译的代码位于jar外部文件系统中。 The IDE compile the code, and then run the program, without building the JAR file. IDE编译代码,然后运行程序,而无需构建JAR文件。 So, your program found the file, because that file still exists in the file system. 因此,您的程序找到了该文件,因为该文件仍存在于文件系统中。

To open a file inside a JAR, you need to use another API: loading the file as a resource. 要在JAR中打开文件,您需要使用另一个API:将文件作为资源加载。

load file within a jar 在罐子里加载文件

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM