Share this page 

Read a text file from a jarTag(s): IO


import java.io.*;
import java.util.*;

public class FileUtils{

  public static List<String> readTextFromJar(String s) {
    InputStream is = null;
    BufferedReader br = null;
    String line;
    ArrayList<String> list = new ArrayList<String>();

    try { 
      is = FileUtils.class.getResourceAsStream(s);
      br = new BufferedReader(new InputStreamReader(is));
      while (null != (line = br.readLine())) {
         list.add(line);
      }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
    finally {
      try {
        if (br != null) br.close();
        if (is != null) is.close();
      }
      catch (IOException e) {
        e.printStackTrace();
      }
    }
    return list;
  }

  public static void main(String args[]) throws IOException{
    List<String> list = FileUtils.readTextFromJar("/datafile1.txt");
    Iterator<String> it = list.iterator();
    while(it.hasNext()) {
      System.out.println(it.next());
    }

    list = FileUtils.readTextFromJar("/test/datafile2.txt");
    it = list.iterator();
    while(it.hasNext()) {
      System.out.println(it.next());
    }
  }
}
Create 2 datafiles.

datafile1.txt in the same directory as FileUtils.class (in the root) and datafile2.txt in a subdirectory called test

[datafile1.txt]

datafile1  line 1
datafile1  line 2
datafile1  line 3
datafile1  line 4
datafile1  line 5

[/test/datafile2.txt]

datafile2  line 1
datafile2  line 2
datafile2  line 3
datafile2  line 4
datafile2  line 5

Create the jar with

>"C:\Program Files\Java\jdk1.5.0\bin\jar" -cf MyJar.jar 
       FileUtils.class datafile.txt test/datafile.txt
Try it :
C> java -cp MyJar.jar FileUtils
The output should be like :
datafile1  line 1
datafile1  line 2
datafile1  line 3
datafile1  line 4
datafile1  line 5
datafile2  line 1
datafile2  line 2
datafile2  line 3
datafile2  line 4
datafile2  line 5
Get the JAR here

With an Applet, it's the same technique

import java.applet.*;
import java.io.*;

public class ReadFromJar extends Applet{

  public void init(){
    readTextFromJar("datafile1.txt");
    readTextFromJar("test/datafile2.txt");
    }

  public void readTextFromJar(String s) {
    String thisLine;
    try {
      InputStream is = getClass().getResourceAsStream(s);
      BufferedReader br = new BufferedReader
         (new InputStreamReader(is));
      while ((thisLine = br.readLine()) != null) {
         System.out.println(thisLine);
         }
    }
    catch (Exception e) {
      e.printStackTrace();
    }
  }
}
Create the JAR
>"C:\Program Files\Java\jdk1.5.0\bin\jar" -cf
    MyJarApplet.jar ReadFromJar.class datafile1.txt test/datafile2.txt
The html
<HTML><HEAD></HEAD><BODY>
<APPLET CODE=ReadFromJar.class width=1 height=1 archive=MyJarApplet.jar>
</APPLET>
See java console for output</BODY></HTML>
Try it here