简体   繁体   English

在Java中,如何从jar文件中检索图像?

[英]In java, how do you retrieve images from a jar file?

I've been having problems exporting my java project to a jar (from Eclipse). 我在将Java项目导出到jar(从Eclipse)时遇到了问题。 There is a file that I've included in the jar named images . 我在jar中包含了一个名为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. 问题是,仅当项目不是 jar形式时,我对这些图像的引用才有效。 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();
    }

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? 当它们全部放在罐子里时,我需要更改什么才能使这些引用起作用?

It is indeed simple: you use the various getResource() methods in java.lang.Class and java.lang.ClassLoader . 这确实很简单:您可以在java.lang.Classjava.lang.ClassLoader使用各种getResource()方法。 For example, in your app, you could just write 例如,在您的应用中,您可以编写

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

This would find the file in an images directory at the root of the jar file. 这将在jar文件根目录的images目录中找到该文件。 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.) getResource()方法的getResource()是,无论文件是否在jar中,它们都可以工作-如果images目录是磁盘上的真实目录,则该目录仍然有效(只要images的父目录是您的课程路径。)

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

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