Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 访问.jar文件中的文件_Java_File_Resources_Jar - Fatal编程技术网

Java 访问.jar文件中的文件

Java 访问.jar文件中的文件,java,file,resources,jar,Java,File,Resources,Jar,可能重复: 在谷歌搜索了几个小时后,我开始完全疯狂了。我也在网站上看到了这个问题的各种变化,但似乎无法让它发挥作用。JFrame需要从ini文件读取数据,我已经创建了一个方法来打开该文件。所述文件存储在jar文件中名为resources的文件夹中 private BufferedReader openIniFile(String filename){ BufferedReader brReader = null; try{ Fi

可能重复:

在谷歌搜索了几个小时后,我开始完全疯狂了。我也在网站上看到了这个问题的各种变化,但似乎无法让它发挥作用。JFrame需要从ini文件读取数据,我已经创建了一个方法来打开该文件。所述文件存储在jar文件中名为resources的文件夹中

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,但似乎找不到一个可行的解决方案


如何使jar文件识别资源?

当您的资源位于jar文件中时,它不再是文件。文件只是文件系统上的一个物理文件。 解决方法:使用。大概是这样的:

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

你看错文件了。如果文件位于JAR中,则不能使用
文件
类。相反,您必须使用
getResourceAsStream()
InputStream
获取到文件中:


我试过了,但没能让它工作:(“没能让它工作”对这没什么帮助。它仍然抛出一个空异常。”“没能让它工作”没什么帮助没有多大帮助,但如果我使用getResourceAsStream,我不能使用File类,对吗?没错。它不是一个文件。我在资源中有一个目录,其中包含所有文件。我如何在目录中导航以访问所有文件,然后使用上面的内容?简单而有效的解决方案:制作一个包含资产或文件的jar,然后作为谢谢。
InputStream in = this.getClass().getResourceAsStream("/resources/" + filename);