title: Java classloader not able to find resource in jar file
body: <p>I have a runnable jar file which is not able to access my resources which reside outside of the default src directory. Based on my understanding from <a href="https://stackoverflow.com/questions/6608795/what-is-the-difference-between-class-getresource-and-classloader-getresource">What is the difference between Class.getResource() and ClassLoader.getResource()</a>, I should be able to access <em>root/res/img/img1.png</em> (see folder setup below) by using the following getResourceFile function:</p>
  
  <pre><code>public class Foo {
  
      private static final ClassLoader CLASS_LOADER = Foo.class.getClassLoader();
  
      public static File getResourceFile(String relativePath) {
          // Since I'm using getClassLoader, the path will resolve starting from 
          // the root of the classpath and it'll take an absolute resource name
          // usage: getResourceFile("img/img1.png")
          // result: Exception in thread "main" java.lang.NullPointerException
          return new File(CLASS_LOADER.getResource(relativePath).getFile());
      }
  }
  </code></pre>
  
  <p><em>folder setup:</em></p>
  
  <pre><code>root/
      src/
          foo/
              bar/
      res/
          img/
              img1.png
          audio/
              audio1.wav
  </code></pre>
  
  <p>The problem arises when I try to execute the jar executable itself. However, the strange thing is that I was not able to replicate this through eclipse IDE which was actually able to resolve the path correctly. I have added the resource directory to the build path via (Project -> Properties -> Java Build Path -> Add Folder) so Java should be able to find the resource folder at runtime.</p>
  
  <p>Is there something I'm missing in terms of generating the jar file? When unpacking the jar file everything seems to be in order with the img and audio directories being in the root (given the above initial folder setup):</p>
  
  <pre><code>foo/
      /bar
  img/
      img1.png
  audio/
      audio1.wav
  </code></pre>