Using FileReader to read a file inside JAR

I have the following code:

private void readFile(String type) {

BufferedReader in = null;

URL file = getClass().getResource("Hello.txt");

try {

in = new BufferedReader(new FileReader(file.getPath()));

} catch (FileNotFoundException ex) {

ex.printStackTrace();

System.out.println("Unable to open file.");

}

}

This works great within the compiler since the file is located within the pakage, however when I try to run the jar it does not work.

I need to figure out a way to keep the file location non-static and be able to read the file from within the JAR

[635 byte] By [dpostelnicua] at [2007-11-27 10:59:45]
# 1

How about:

http://java.sun.com/j2se/1.4.2/docs/api/java/util/zip/ZipFile.html

InputStream getInputStream(ZipEntry entry)

Returns an input stream for reading the contents of the specified zip file entry.

TuringPesta at 2007-7-29 12:25:15 > top of Java-index,Java Essentials,Java Programming...
# 2

You can't use a FileReader to read entries of a jar file on the Classpath, since those are not Files in the sense that they are placed in the Filesystem.

Simply use getResourceAsStream() instead of getResource(). This will give you a InputStream, which you can then wrap in a InputStreamReader. This can again be wrapped in the BufferedReader and you can continue as you're used to.

JoachimSauera at 2007-7-29 12:25:15 > top of Java-index,Java Essentials,Java Programming...
# 3

that worked thanks for the help

dpostelnicua at 2007-7-29 12:25:16 > top of Java-index,Java Essentials,Java Programming...