Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I reference a resource in Java?

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?

like image 907
Chris Knight Avatar asked Sep 16 '10 15:09

Chris Knight


People also ask

How to read data from Resource file in Java?

In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath. The getResourceAsStream method returns an InputStream . // the stream holding the file content InputStream is = getClass(). getClassLoader().

Can you use references in Java?

Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.

How to get resources file path in Java?

The simplest approach uses an instance of the java. io. File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = file.

How to get xml file from resources in Java?

You need to make sure that Eclipse includes /resources folder into the application classpath. Open your launcher from Run Configurations , goto Classpath tab and if it's not there - add it. The file can be read with this. getClass().


1 Answers

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");
like image 80
Jon Skeet Avatar answered Sep 28 '22 08:09

Jon Skeet