how to add and read resource file from jar

点点圈 提交于 2019-12-29 01:24:09

问题


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

scr -> main-> java

        ->resources

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

myjar.jar -> com (source code)

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

I tried accessing using

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

but got null..

Let me know what steps are wrong ?


回答1:


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




回答2:


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

For instance, you have class A and resource test.txt in 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").

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



来源:https://stackoverflow.com/questions/5466685/how-to-add-and-read-resource-file-from-jar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!