Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

java - 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. 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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").


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...