简体   繁体   English

使用.getResource()从.jar获取文件

[英]Getting File from .jar using .getResource()

I'm trying to acces a File inside the .jar. 我正在尝试访问.jar中的文件。 In Netbeans, this: 在Netbeans中,这是:

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

Prints out: 打印输出:

true

After building however, it prints false. 但是,构建之后,它会打印false。

The file is definitely in the .jar, next to the .class file, and something like this: 该文件肯定在.jar中,在.class文件旁边,如下所示:

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? 如何将Image.jpg作为文件对象访问?

The file is packed, try 该文件已打包,请尝试

resource.getInputStream() 

or 要么

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

Hope it helps 希望能帮助到你

You don't get a File object to it. 您没有获得File对象。 Its an entry in a JAR not a File on the Filesystem. 它是JAR中的条目,而不是文件系统上的文件。 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. 通过将InputStream复制到文件系统来创建文件,找到一种使用InputStream的方法,或者始终扩展JAR。

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

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