TheScottymo
TheScottymo

Reputation: 54

Reading a text file from a jar

I'm having trouble reading a text file from inside a jar. I managed it while it was unzipped but now that I've archived it it won't work. The jar has:

Now, at the moment I'm using a BufferedReader and a FileReader

 f = new FileReader("Splash.txt");
 in = new BufferedReader(f);

but from googling around I know that that only reads files from outside of the jar.

My question is: How do I read a file from inside the jar?

Upvotes: 0

Views: 735

Answers (3)

Brandon
Brandon

Reputation: 23498

A jar is just a zip file and can be read like this..

ZipFile file = new ZipFile("/home/Desktop/myjar.jar");
Enumeration<? extends ZipEntry> entries = file.entries();

while (entries.hasMoreElements()) {
    ZipEntry entry = entries.nextElement();

    if (entry.getName().startsWith("splash")) {
        try (BufferedReader reader = new BufferedReader(new InputStreamReader(file.getInputStream(entry)))) {
            String line = null;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

Upvotes: 0

MadProgrammer
MadProgrammer

Reputation: 347194

The problem is Splash.txt isn't a file, its series of bytes within in a (lightly) compressed file which has a named entry within a table of contents as specified by the Jar/Zip standard.

This measn you can use FileReader to read the file, instead, you need to access it via the Class resource management API, for example..

getClass().getResourceAsStream("/Splash.txt");

Or, if you're trying to read it from static context

Splash.class.getResourceAsStream("/Splash.txt");

Don't forget, you become responsible for closing the InputStream when you are done, for example...

try (InputStream is = getClass().getResourceAsStream("/Splash.txt")) {....

Upvotes: 0

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 279910

Assuming you're executing the BTA.jar, you can use

InputStream in = YourClass.class.getResourceAsStream("/Splash.txt");

to retrieve an InputStream and pass it to the BufferedReader through an InputStreamReader.

The rules for the format of the path to pass to the method are defined here, in the javadoc for the Class class.

Upvotes: 2

Related Questions