Saturday Aug 31

Key Concepts

Read an input stream with or without the classloader

Monday, 29 August 2011 09:06
AddThis Social Bookmark Button

Java read an inputstream using the class loader

Loading an input stream in Java

If you want to load a resource using a specified name from the search path in your java application you need to take into account the following rules : 

If your file is located in a file structure like this : 


You can reach it using the following java snippet : 

Load an inputStream using the classloader in Java 

InputStream reportTemplate = getClass().getClassLoader().getResourceAsStream("reporting/sampleReport.xml");

Ger resource as stream should not use a shlash at the beginning of the path

The method getResourceasStream() in ClassLoader use the given String as the name of the resource without applying any absolute/relative transformation (see the methods in Class). The name should not have a leading slash (/).

Or if you don't access it using the class loader you need to use the slash (/) at the beginning of your resource path.

Get a resource as stream without classloader

InputStream reportTemplate2 = getClass().getResourceAsStream("/reporting/sampleReport.xml");

Related articles :

If you have any remark or questions feel free to put a comment.If you enjoyed this tutorial and want to promote it don't hesitate to click on

Tags: java, stream, file, input, resource, classloader, slash

Add comment

Security code

Java Tutorial on Facebook