title: (Java) Trouble going between URLs and files with a .jar file
body: <p>I'm making a rather big program in java. It has lots of files, including images, audio, and text files. When I'm running from Eclipse, the code I use works fine. However, I always have trouble gaining access to them from a .jar file that's on its own.</p>
  
  <p>I'll give you an example of how I'm coding this.</p>
  
  <p>For the BufferedImage, I have it this way:</p>
  
  <pre><code>File bgImgFile = new File("images/nature.jpg");
  BufferedImage bgImg = ImageIO.read(bgImgFile);
  </code></pre>
  
  <p>For the AudioInputStream, I have:</p>
  
  <pre><code>File soundFile = new File("audio/two.wav");
  AudioInputStream audioIn = AudioSystem.getAudioInputStream(soundFile);
  </code></pre>
  
  <p>And for the text file, I have:</p>
  
  <pre><code>FileReader reader = new FileReader("scripts/0.txt");
  </code></pre>
  
  <p>This all works fine for when I'm in Eclipse. However, I'm thinking about what I'll want to do for distribution. I want to have a .jar file that can run anywhere, and doesn't need to be in the same directory as those folders containing the files. I've done this before and it's worked fine.</p>
  
  <p>This is what I tried to do for the image:</p>
  
  <pre><code>URL bgFileUrl = MainClass.class.getClassLoader().getResource("images/nature.jpg");
  File bgImgFile = new File(bgFileUrl.getFile());
  BufferedImage bgImg = ImageIO.read(bgImgFile);
  </code></pre>
  
  <p>I did similar things for the audio and text file. However, even when I tried in different combinations of having the files themselves in the same directory, having a slash in front of the plain file name, etc., nothing worked. I want to be able to include these files in the .jar file so I don't have to run the .jar from that specific folder.</p>
  
  <p>One thing I don't understand is that, when I opened up the .jar file made using my original code, the images, audio, and scripts folders were in there and they had my files. They were there. However, when I tried to run it, I got an IIOException ("Can't read input file!") and a NullPointerException, even though I was using the same code as before.</p>
  
  <p>How do I make it so the files are included in the .jar file so it can run on its own?</p>
  
  <p>Thanks for the help!</p>