Monday, August 1, 2005

reading a file that resides inside a jar

Most of the time, we end up reading a text or properties file that is bundled with the application. If the application jar is extracted and run, we wouldnt have problem in reading the file since it is in the file system now. But, sometimes we would be running the application as it is, may be using "java -jar" command or an Applet for example. In this case, the application need to read the file which resides in the same application jar.
import java.io.*;

public class TxtRead

{

public void read() throws IOException

{
InputStream ios=getClass().

getResourceAsStream("test.txt");

BufferedReader reader=new BufferedReader(

new InputStreamReader(ios));

String line=reader.readLine();



while (line != null)

{

System.out.println(line);

line=reader.readLine();

}

}



public static void main(String[] arg)

throws IOException

{

new TxtRead().read();

}

}

/home/poorna> cat test.txt
This is a text file

/home/poorna> javac TxtRead.java

# Create a manifest file in META-INF directory with "Main-Class: TxtRead"

/home/poorna> jar -cvfm txt.jar META-INF\MANIFEST.MF TxtRead.class test.txt


/home/poorna> java -jar txt.jar
This is a text file

No comments: