Note that there are some explanatory texts on larger screens.

plurals
  1. POwhat is the difference between reading a resource from the class versus class loader?
    primarykey
    data
    text
    <p>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 <code>class.getResourceAsStream("/test.txt")</code> and in another case, my code calls <code>class.getClassLoader().getResourceAsStream("/test.txt")</code>. </p> <p>The first call gets the correct data but the second one doesn't get anything. any idea?</p> <pre><code>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) { } } } </code></pre> <p>let's say i have 2 jar files</p> <ul> <li>first.jar : contains TestLoadResourcesByClass.class (code to read test.txt)</li> <li>second.jar : contains "test.txt" at the root </li> </ul> <p>and then i run my code as follows</p> <pre><code>java -cp first.jar;second.jar;commons-io-2.4.jar test.TestLoadByClass </code></pre> <p>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).</p> <p>any idea on what's going on?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload