Jane Wayne
Jane Wayne

Reputation: 8855

what is the difference between reading a resource from the class versus class loader?

I am trying to read a text file, "text.txt", packaged at the root as a part of my jar file. in one case, my code calls class.getResourceAsStream("/test.txt") and in another case, my code calls class.getClassLoader().getResourceAsStream("/test.txt").

The first call gets the correct data but the second one doesn't get anything. any idea?

public static void main(String[] args) {
 InputStream is = null;
 try {
  is = TestLoadResourcesByClass.class.getResourceAsStream("/test.txt");
  StringWriter writer = new StringWriter();
  IOUtils.copy(is, writer);
  System.out.println(writer.toString());
 } catch(Exception ex) {
  ex.printStackTrace();
 } finally {
  if(null != is) { try { is.close(); } catch(Exception ex) { } }
 }
}

public static void main(String[] args) {
 InputStream is = null;
 try {
  is = TestLoadResourcesByClassLoader.class.getClassLoader().getResourceAsStream("/test.txt");
  StringWriter writer = new StringWriter();
  IOUtils.copy(is, writer);
  System.out.println(writer.toString());
 } catch(Exception ex) {
   ex.printStackTrace();
 } finally {
  if(null != is) { try { is.close(); } catch(Exception ex) { }
 }
}

let's say i have 2 jar files

and then i run my code as follows

java -cp first.jar;second.jar;commons-io-2.4.jar test.TestLoadByClass

i also get no output at the console. is that because the classes/resources in second.jar have not been loaded? in fact, i get a null pointer exception (input stream is null).

any idea on what's going on?

Upvotes: 1

Views: 124

Answers (1)

Geo
Geo

Reputation: 760

It is explained in the javadoc for Class.getResourceAsStream. That method removes the / from the start of resource names to create the absolute resource name that it gives to ClassLoader.getResourceAsStream. If you want to call ClassLoader.getResourceAsStream directly then you should omit the / at the start.

Upvotes: 2

Related Questions