How to Read a File from CLASSPATH in Java

This can be done in two simple ways

 

Using ClassLoader.getResourceAsStream

This method can be used to load any file from CLASSPATH
InputStream in =this.getClass().getClassLoader().getResourceAsStream(“MyFile.txt”);

 

Using Class.getResourceAsStream

This method can be used to load files using relative path to the package of the class
InputStream in =this.getClass().getResourceAsStream(“SomeTextFile.txt”);

 

This method can also be used to load any files from CLASSPATH by prefixing a “/”