java 如何从jar中添加和读取资源文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5466685/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 11:15:34  来源:igfitidea点击:

how to add and read resource file from jar

javajarmaven

提问by harshit

I have hibernate.cfg.xml and test.txt in the path which i read by java program. Now when i created the jar using maven those files were not present. So i read that i should put in the resources folder , so now my directory structure is

我在java程序读取的路径中有hibernate.cfg.xml和test.txt。现在,当我使用 maven 创建 jar 时,这些文件不存在。所以我读到我应该放在资源文件夹中,所以现在我的目录结构是

scr -> main-> java

        ->resources

scr -> main-> java

        ->resources

Now i can see the files in the jar but they are not inside resource folder it bascically

现在我可以看到 jar 中的文件,但它们基本上不在资源文件夹中

myjar.jar -> com (source code)

       -> META -INF
       -> hibernate.cfg.xml
       -> test.txt

myjar.jar -> com(源代码)

       -> META -INF
       -> hibernate.cfg.xml
       -> test.txt

I tried accessing using

我尝试访问使用

getClass().getResourceAsStream("test.txt")

getClass().getResourceAsStream("test.txt")

but got null..

但得到了空..

Let me know what steps are wrong ?

让我知道哪些步骤是错误的?

回答by pajton

getClass().getResourceAsStream(name)searches for the resource in the same dir as the class for which this method is called is in.

getClass().getResourceAsStream(name)在与调用此方法的类相同的目录中搜索资源。

For instance, you have class Aand resource test.txtin the same dir the you call getClass().getResourceAsStream("test.txt"). If it's located in some subdir, you need to express that in name: getClass().getResourceAsStream("subdir/test.txt").

例如,您在您调用的同一个目录中拥有类A和资源。如果它位于某个子目录中,则需要在: 中表示。test.txtgetClass().getResourceAsStream("test.txt")namegetClass().getResourceAsStream("subdir/test.txt")

I haven't tested that, but looking in dirs above current should be possible with: getClass().getResourceAsStream("../test.txt").

我没有测试过这一点,但看在高于目前迪尔斯应该是可能的:getClass().getResourceAsStream("../test.txt")

回答by Raghuram

Looking at this article, Does getClass().getResourceAsStream("/test.txt")make a difference?

看了这篇文章,有getClass().getResourceAsStream("/test.txt")什么区别吗?