简体   繁体   English

导出的Jar文件将无法读取jar中的文件

[英]Exported Jar file won't read file inside jar

In the code sample below, when I test the code in Eclipse it works just fine. 在下面的代码示例中,当我在Eclipse中测试代码时,它可以正常工作。 However, when I export the jar file and test it via the command line, it throws an error: IIOException: Can't read input file! 但是,当我导出jar文件并通过命令行对其进行测试时,它将引发错误: IIOException: Can't read input file!

private BufferedImage img = null;
private String imgSource;

if (img == null)
{
    try {
        URL url = getClass().getResource("Images/questionMark.png");
        System.out.println(url.getPath()); 
        /* This prints: file:/C:/Users/Keno/Documents/javaFile.jar!/javaFile/Images/questionMark.png */
        File file = new File(url.getPath());
        img = ImageIO.read(file);
        imgSource = file.getName();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

The file I want to get is located inside the Images folder which is inside the javaFile package. 我要获取的文件位于javaFile包内的Images文件夹内。 I've noticed one thing that may indicate the problem. 我注意到一件事可能表明问题所在。

  1. In the print statement I have, I notice an exclamation sign at the end of the javaFile.jar section. 在我拥有的打印语句中,我注意到javaFile.jar节末尾有一个感叹号。 Is that correct? 那是对的吗? Could that indicate an issue with the file or structure? 可以说明文件或结构有问题吗?

Also, just in case someone has a better suggestion as to how I should load the file, I'll tell you my intentions. 另外,以防万一有人对我应该如何加载文件有更好的建议,我将告诉您我的意图。 I would like to load the file from a relative location (Images folder) in the jar. 我想从罐子中的相对位置(图像文件夹)加载文件。 I would like to display it (Already done in my actual code) and also store the location to be passed later on to another function (also done). 我想显示它(已经在我的实际代码中完成了),并且还存储了以后要传递给另一个函数的位置(也已经完成了)。

try this 尝试这个

public void test() {
    try(InputStream is = getClass().getResourceAsStream("Images/questionMark.png")) {
        ImageIO.read(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

You should try to check if your class is in the same directory than Images inside your jar. 您应该尝试检查您的类是否与jar中的Images位于同一目录中。

   |
   |- Your class
   |- Images
       |- questionMark.png

Also, have you tried using directly your url object ? 另外,您是否尝试过直接使用url对象?

File file = new File(url);

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

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