Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

file io - How do I reference a resource in Java?

I need to read a file in my code. It physically resides here:

C:eclipseWorkspaceProjectAsrccomcompanysomePackageMyFile.txt

I've put it in a source package so that when I create a runnable jar file (Export->Runnable JAR file) it gets included in the jar. Originally I had it in the project root (and also tried a normal sub folder), but the export wasn't including it in the jar.

If in my code I do:

File myFile = new File("com\company\somePackage\MyFile.txt");

the jar file correctly locates the file, but running locally (Run As->Java Main application) throws a file not found exception because it expects it to be:

File myFile = new File("src\com\company\somePackage\MyFile.txt");

But this fails in my jar file. So my question is, how do I make this concept work for both running locally and in my jar file?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Use ClassLoader.getResourceAsStream or Class.getResourceAsStream. The main difference between the two is that the ClassLoader version always uses an "absolute" path (within the jar file or whatever) whereas the Class version is relative to the class itself, unless you prefix the path with /.

So if you have a class com.company.somePackage.SomeClass and com.company.other.AnyClass (within the same classloader as the resource) you could use:

SomeClass.class.getResourceAsStream("MyFile.txt")

or

AnyClass.class.getClassLoader()
              .getResourceAsStream("com/company/somePackage/MyFile.txt");

or

AnyClass.class.getResourceAsStream("/com/company/somePackage/MyFile.txt");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...