[英]how to add and read resource file from jar
I have hibernate.cfg.xml and test.txt in the path which i read by java program. 我通过Java程序读取的路径中有hibernate.cfg.xml和test.txt。 Now when i created the jar using maven those files were not present.
现在,当我使用maven创建jar时,这些文件不存在。 So i read that i should put in the resources folder , so now my directory structure is
所以我读到我应该放在资源文件夹中,所以现在我的目录结构是
scr -> main-> java
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)
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 ? 让我知道哪些步骤是错误的?
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 A
and resource test.txt
in the same dir the you call getClass().getResourceAsStream("test.txt")
. 例如,您在与调用
getClass().getResourceAsStream("test.txt")
相同的目录中具有类A
和资源test.txt
。 If it's located in some subdir, you need to express that in name
: getClass().getResourceAsStream("subdir/test.txt")
. 如果它位于某个子目录中,则需要以
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")
. 我还没有测试过,但是应该可以使用
getClass().getResourceAsStream("../test.txt")
查找高于当前的目录。
看这篇文章 , getClass().getResourceAsStream("/test.txt")
有什么不同吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.