Reading resources from a JAR file

For this example, create the following directory structure:

   myresources
       |
       --- text
       |    |
       |    --- <a href="http://www.esus.com/example.txt">example.txt</a>
       |
       --- image
            |
            --- <a href="http://www.esus.com/images/djkrush.jpg">djkrush.jpg</a>

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

mymanifest:

Main-Class: Main
 

(notice the extra carriage-return!)

Main.java:

import javax.swing.*;
import java.util.*;
import java.awt.*;
import java.net.*;
import java.io.*;
   
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 = ");
      System.out.println(txt);
 
      System.exit(0);
   }
 
   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

run:

   java -jar res.jar

output:

img = sun.awt.windows.WImage@c4b3fd8b
 
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