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

查看:133
本文介绍了访问.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文件识别资源? p>

How can I make the jar file recognize the resource?

推荐答案

当您的资源在JAR文件中时,它不再是File。文件只是文件系统上的物理文件。
解决方案:使用的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天全站免登陆