Getting the Streams Right

classLoader.getResourceAsStream
You should use classloader only for reading INSIDE a file like reading text from inside a text file or properties from inside a properties file. It is useful only for reading from text files etc. The file should be on the classpath . Loading a class means making the class available in your code. Getting a resource as stream means giving access to some “resource” from the classpath. Resource here is any other file other than java-classes.

classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/sql.properties”);

The above code is used to load a class such as a properties file or an xml file.
The input stream may be passed onto suitable constructors wherever permissible.
The getResourceAsStream is basic java. It reads resources from the classpath. There’s nothing servlet-ish about it. It would work the same with a standalone java application.

classloader.getResource()
If you do want the file literally as a file (not to read it), then use classloader.getResource(). This returns a URL, which would look like this

file:///c:/temp/file.txt

if it is on the classpath.
Pattern:

file:///{absolutepath}

Remove the leading file:/// and you have the path to the file.
This uses the same technique as getResourceAsStream but returns a URL instead of inputstream

For example here you use getResourceAsStream() to read from a file to load properties:

// the answer lies in not specifying the absolute/relative path of
//sql.properties.
// instead load the resource from the classpath using
//classloader.getResourceAsStream()
// this is how to go about it
// create a package inside the EJB project called
//com/mattiz/test/resources/sql.properties or some name like that
// and put the sql.properties file into it.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
if (classLoader == null)
classLoader = this.getClass().getClassLoader();
InputStream is = classLoader.getResourceAsStream(“com/mattiz/test/resources/sql.properties”);
Properties sqlCache = new Properties();
sqlCache.load(is);

For simple read access you would do the following where stream is an input stream


BufferedReader br = new BufferedReader(new InputStreamReader(stream));
//printing out contents if text file
while((line = br.readLine()) != null)
{
//iterate through the contents
System.out.print(line);
}

The constructor of the transformer class which is used in xsl transformations takes an inputStream as a parameter directly. This input stream may be obtained from an xsl file using the getResourceAsStream() method.

About cuppajavamattiz
Matty Jacob - Avid technical blogger with interests in J2EE, Web Application Servers, Web frameworks, Open source libraries, Relational Databases, Web Services, Source control repositories, ETL, IDE Tools and related technologies.

Comments are closed.

%d bloggers like this: