Getting File from .jar using .getResource()

六眼飞鱼酱① 提交于 2019-12-31 06:47:48

问题


I'm trying to acces a File inside the .jar. In Netbeans, this:

System.out.println(new File(this.getClass().getResource("Image.jpg").getFile()).exists());

Prints out:

true

After building however, it prints false.

The file is definitely in the .jar, next to the .class file, and something like this:

new Frame(){
        @Override
        public void paint(Graphics g){
            try{
                g.drawImage(ImageIO.read(this.getClass().getResource("Image.jpg")), 0, 0, this);
            } catch(Exception e){e.printStackTrace();}
        }
    }.setVisible(true);

does paint the image after building.

How can I acces the Image.jpg as a File object?


回答1:


The file is packed, try

resource.getInputStream() 

or

InputStream streamOfYourImg = this.getClass().getRessourceAsStream("com/package/resources/image.jpeg");

Hope it helps




回答2:


You don't get a File object to it. Its an entry in a JAR not a File on the Filesystem. You have a few options. Create a File by copying the InputStream to the Filesystem, FInd a way to use the InputStream instead, or always have your JAR expanded.



来源:https://stackoverflow.com/questions/10190470/getting-file-from-jar-using-getresource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!