How to read files from CLASSPATH in Java

This is one learning from my previous project in 2009.

The most platform-independent and flexible way in Java to load resources such as files is to read the resource from CLASSPATH. This way, as long as the resource’s location is added to CLASSPATH, the resource can be anywhere on the disk.

Java provides a method named getResourceAsStream() for this purpose. This method is present in both Class and ClassLoader classes. There are very subtle differences between these two methods, which if not understood properly, will lead to confusion.

Using ClassLoader.getResourceAsStream(),

While using ClassLoader.getResourceAsStream() method, the name of the resource should not be preceded with leading slash (/) in any circumstances. This is because from ClassLoader all paths are already absolute and there is no context from which they could be relative. Therefore the question of whether or not to use leading slash (/) should not arise. If you add leading slash in front of the resource name, InputStream will always be null.

To use ClassLoader.getResourceAsStream(),

[1] In CLASSPATH add the directory where someFile.txt resides.

[2] Use the following code to read the resource.

InputStream in = this.getClass().getClassLoader().getResourceAsStream(“SomeFile.txt”);

Using Class.getResourceAsStream(),

(a) If the resource and the Java class which is reading the resource are in the same directory then there is no need to use a leading slash (/). You can directly use the following line of code to read the resource.

InputStream in = this.getClass().getResourceAsStream(“SomeFile.txt”);

(b) If the resource and the Java class which is reading the resource are in different directories then you have to use a leading slash (/).

[1] In CLASSPATH add the directory where someFile.txt resides.

[2] Use the following code to read the resource.

InputStream in = this.getClass().getResourceAsStream(“/SomeFile.txt”);

Important Note:

When we are using a managed environment i.e. in case of application servers, CLASSPATH entry has to be made in the server’s start up script. For example in WebLogic, CLASSPATH entry has to be appended to the one already present in startWebLogic.cmd (startWebLogic.sh in Unix environments) in DOMAIN_HOME\bin directory.

Reference:

1.http://stackoverflow.com/questions/1464291/how-to-really-read-text-file-from-classpath-in-java


Comments

Leave a Reply

Discover more from Chai's Blog

Subscribe now to keep reading and get access to the full archive.

Continue reading