java导出可执行jar包后,工程中使用的图片找不到路径,但是在myeclipse中运行没错

java导出可执行jar包后,工程中使用的图片找不到路径,但是在myeclipse中运行没错

问题描述:

我在一个jpanel中放置一张图片,但是导出为可执行的jar包后,这张图片找不到了,提示不能加载此图片,程序中使用的是Classloader.getSystemResource("工程下的图片"),java导出可执行jar包后,工程中使用的图片找不到路径,但是在myeclipse中运行没错,请问各位大哥,怎么实现呢?

我测试了一下,我把图标放在类的同目录下,通过Class.getResource返回的地址来构造File对象,获取不到图片;而直接通过Class.getResourceAsStream能返回图片数据。下面是我的测试代码:
[code="java"]
package image;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class ImageLoader {

public static void main(String[] args) throws Exception {

    String url = ImageLoader.class.getResource("image.jpg").toString();
    System.out.println("find the image : " + url);

    //在jar包内运行无法访问image
    File image = new File(url);
    if (image != null && image.exists()) {
        System.out.println("The image size : " + image.length());
    }

    //在jar包内可以获取图片数据
    InputStream is = ImageLoader.class.getResourceAsStream("image.jpg");
    if (is != null) {
        System.out.println("The image exists ");

        FileOutputStream out = new FileOutputStream("c:/new.jpg");
        byte[] temp = new byte[1024];
        int len;
        while((len = is.read(temp)) > 0) {
            out.write(temp , 0 ,len);
        }

        is.close();
        out.close();
        System.out.println("The image finish to copy");
    } else {
        System.out.println("The image does not exist");
    }

}

}
[/code]
这个在jar运行也测试过,可以把图片复制到c盘,我想你的需求也类似,至少要能得到图片数据。

[code="java"] getClass().getResource("工程下的图片");
以类(类路径)为基准查找[/code]

把你的图片放到SRC目录下,打包时一块打到JAR包里

使用时

getClass().getResource("/");