How do I reference a resource in Java?

浪子不回头ぞ 提交于 2019-12-17 23:48:04

问题


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

C:\eclipseWorkspace\ProjectA\src\com\company\somePackage\MyFile.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?


回答1:


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



回答2:


If I have placed i file in a jar file, it only worked if and only if I used

...getResourceAsStream("com/company/somePackage/MyFile.txt")

If I used a File object it never worked. I got also the FileNotFound exception. Now, I stay with the InputStream object.



来源:https://stackoverflow.com/questions/3727994/how-do-i-reference-a-resource-in-java

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