在java中,如何从jar文件中检索图像? [英] In java, how do you retrieve images from a jar file?

查看:129
本文介绍了在java中,如何从jar文件中检索图像?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在将java项目导出到jar(来自Eclipse)时遇到了问题。我在jar中包含了一个名为 images 的文件。它包含我的项目使用的所有图像文件。问题是,我对这些图像的引用仅在项目不是的jar形式时才有效。我无法弄清楚为什么,我想知道是否需要更改图像引用的措辞。这就是我正在做的参考图像:

I've been having problems exporting my java project to a jar (from Eclipse). There is a file that I've included in the jar named images. It contains all of the image files used by my project. The problem is, my references to those images only work when the project isn't in jar form. I can't figure out why and I'm wondering if I need to change the wording of the image references. This is what I'm doing to reference images:

    URL treeURL = null;
    Image tree = null;
    File pathToTheTree = new File("images/tree.png");
    try {
        treeURL = pathToTheTree.toURL();
    } catch (MalformedURLException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }
    try {
        tree = ImageIO.read(treeURL);
    } catch(IOException e) {
        e.printStackTrace();
    }

很可能这是一个简单的问题,因为我是编码的初学者。当这些引用全部放在jar中时,我需要更改以使这些引用有效吗?

Most likely it is a simple problem, as I'm a beginner at coding. What do I need to change to make these references work when it's all in a jar?

推荐答案

这确实很简单:你使用 java.lang.Class java.lang.ClassLoader中的各种 getResource()方法。例如,在你的应用程序中,你可以写

It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader. For example, in your app, you could just write

treeURL = getClass().getResource("/images/tree.png");

这将在图像中找到该文件 jar文件根目录下的目录。关于 getResource()方法的好处是,无论文件是否在jar中,它们都能正常工作 - 如果 images 目录是磁盘上的真实目录,这仍然有用(只要 images 的父级是你的类路径的一部分。)

This would find the file in an images directory at the root of the jar file. The nice thing about the getResource() methods is that they work whether the files are in a jar or not -- if the images directory is a real directory on disk, this will still work (as long as the parent of images is part of your class path.)

这篇关于在java中,如何从jar文件中检索图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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