Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between ClassLoader.getSystemResourceAsStream and getClass().getResourceAsStream()

Tags:

java

Given this code:

/* 1 */ InputStream in1 = ClassLoader.getSystemResourceAsStream("foobar.txt");
/* 2 */ InputStream in2 = this.getClass().getResourceAsStream("/foobar.txt");

Do both return the same resource (I think the answer's "yes")?

Do they both access the "same" classpath? Why is the method name in #1 "get System ResourceAsStream", but for #2 it's just "getResourceAsStream"?

Thanks

like image 314
Michael Avatar asked Sep 30 '11 19:09

Michael


2 Answers

The key difference is the class loader.

The following uses the System ClassLoader
ClassLoader.getSystemResourceAsStream("foobar.txt");

While this one uses the Classloader returned by getClass()
this.getClass().getResourceAsStream("/foobar.txt");

In other words, whether both statements behave exactly the same or not, depends on the application classloader. For a simple application, both refer to the same classloader. However, for most applications (like a web application running within Servlet container), that will not be the case.

In general, I would say getClass().getResourceAsStream() will be the better choice as it will use the same classloader as the Class the code belongs to.

like image 81
Zarick Lau Avatar answered Sep 30 '22 07:09

Zarick Lau


According to the javadoc

Open for reading, a resource of the specified name from the search path used to load classes. This method locates the resource through the system class loader (see getSystemClassLoader()).

The classloader used to load this is not necessarily the system classloader. In a simple desktop app, this will probably be true. But webapps - amongst other things - typically have more complex classpath hierarchies and so that won't necessarily be the same. In a complex classpath, therefore what's returned will also depend on how many copies of 'foobar.txt' are floating around your classpath.

The short answer is that you can't assume that they will return a stream for the same resource.

like image 41
sblundy Avatar answered Sep 30 '22 07:09

sblundy