Reading resources from a JAR file

For this example, create the following directory structure:

       --- text
       |    |
       |    --- <a href="">example.txt</a>
       --- image
            --- <a href="">djkrush.jpg</a>

Create a manifest file to specify the class that contains the main method.


Main-Class: Main

(notice the extra carriage-return!)

import javax.swing.*;
import java.util.*;
import java.awt.*;
public class Main {
   public static void main(String[] args) throws Exception {
      Image img = getImageFileFromJar("myresources/images/djkrush.jpg");
      String txt = getTxtFileFromJar("myresources/text/example.txt");
      System.out.println("img = " + img + "n");
      System.out.println("txt = ");
   public static Image getImageFileFromJar(String file) throws Exception {
      URL url = Main.class.getResource(file);
      return new ImageIcon(url).getImage();
   public static String getTxtFileFromJar(String file) throws Exception {
      InputStream in = Main.class.getResourceAsStream(file);
      BufferedReader br =new BufferedReader(new InputStreamReader(in));
      String line;
      StringBuffer sb = new StringBuffer();    
      while((line = br.readLine()) !=null) {
        sb.append(line + "rn");
      return sb.toString();

jar everything up:

   jar cmfv mymanifest res.jar myresources Main.class


   java -jar res.jar


img =
txt = 
It is, in fact, nothing short of a miracle that the modern methods 
of instruction have not yet entirely strangled the holy curiosity 
of inquiry; for this delicate little plant, aside from stimulation, 
stands mainly in need of freedom; without this it goes to wrack and 
ruin without fail. It is a very grave mistake to think that the 
enjoyment of seeing and searching can promoted by means of coercion 
and sense of duty. To the contrary, I believe that it would be 
possible to rob even a healthy beast of prey of its voraciousness, 
if it were possible, with the aid of a whip, to force the beast to 
devour continuously, even when not hungry,especiallyif the food, 
handed out under such coercion, were to be selected accordingly. 
Albert Einstein