导出的jar文件不会读取jar内的文件 [英] Exported Jar file won't read file inside jar

查看:160
本文介绍了导出的jar文件不会读取jar内的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的代码示例中,当我在Eclipse中测试代码时,工作正常。但是,当我导出jar文件并通过命令行测试它时,它会抛出一个错误: IIOException:无法读取输入文件!

In the code sample below, when I test the code in Eclipse it works just fine. However, when I export the jar file and test it via the command line, it throws an error: 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();
    }
}

我想要的文件位于图像内文件夹位于 javaFile 包内。我注意到有一件事可能表明问题。

The file I want to get is located inside the Images folder which is inside the javaFile package. I've noticed one thing that may indicate the problem.


  1. 在print语句中,我注意到javaFile.jar部分末尾有一个感叹号。那是对的吗?这可能是文件或结构的问题吗?






另外,有人对我如何加载文件有更好的建议,我会告诉你我的意图。我想将文件从相对位置(Images文件夹)加载到jar中。我想显示它(已经在我的实际代码中完成了),并将要稍后传递的位置存储到另一个函数(也已完成)。


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).

推荐答案

尝试这个

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

这篇关于导出的jar文件不会读取jar内的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆