访问 .jar 文件中的文件 [英] Accessing a file inside a .jar file

查看:34
本文介绍了访问 .jar 文件中的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何从一个 Java jar 文件?

在谷歌搜索几个小时后开始完全疯了.我还在网站上看到了该问题的变体,但似乎无法使其正常工作.JFrame 需要从 ini 文件中读取数据,我创建了一个方法来打开该文件.所述文件存储在 jar 文件内称为资源的文件夹中.

Starting to go completely bonkers over this after googling for hours. I've also seen variations of the question on the site but can't seem to get it working. A JFrame needs to read data from a ini file and I've created a method to open said file. Said file is stored in a folder called resources inside a jar file.

private BufferedReader openIniFile(String filename){
    BufferedReader brReader = null;                 
    try{
        File fileObj = new File(this.getClass().getResource("/resources/" + filename).toURI()); // The fileobject of the file to read
        if(fileObj.exists())                                            
            brReader = new BufferedReader(new FileReader(fileObj));                     

    } catch(Exception e){
        System.err.println("Exception while opening file: " + e.getMessage()); 

    }

    return null;
}

当我在编译后运行代码时,这当然可以完美运行,但在导出到 .jar 文件后会引发异常.我已经研究过使用 InputStream、FileInputStream,但似乎找不到可行的解决方案.

This of course works perfectly when I'm running the code after compilation, but throws an exception after being exported to a .jar file. I've looked into using InputStream, FileInputStream but can't seem to find a solution that would work.

如何让jar文件识别资源?

How can I make the jar file recognize the resource?

推荐答案

当您的资源在 JAR 文件中时,它就不再是文件了.文件只是文件系统上的物理文件.解决方案:使用 getResourceAsStream.像这样:

When your resourse is in JAR file, it's not a File anymore. A File is only a physical file on the filesystem. Solution: use getResourceAsStream. Something like this:

new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("/resources/" + filename)))

这篇关于访问 .jar 文件中的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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