Dylan Wheeler
Dylan Wheeler

Reputation: 7074

How would I go about reading from a packaged file?

I have a file that I packaged in my JAR file, but I can't figure out how I would read the text file and store it into a String variable. Any ideas anyone?

Upvotes: 0

Views: 89

Answers (3)

JJ.
JJ.

Reputation: 5475

This approach would work for any jar file, even if it's not in your current project/library/classpath:

String myJarFilename ="C:\\path\\to\\myfile.jar";
JarFile jarFile = new JarFile(myJarFilename);
JarEntry jarEntry = jarFile.getJarEntry("mytextfile.txt");

if (jarEntry != null)
{
    InputStream is = jarFile.getInputStream(jarEntry);
    // do normal stuff here to read string from inputstream

    InputStreamReader isr = new InputStreamReader(is);
    byte[] charArr = new byte[2048];
    int bytesRead = 0;
    StringBuffer sb = new StringBuffer();
    while (bytesRead = is.read(charArr, 0, 2048) > 0)
    {
        sb.append(charArr, 0, bytesRead);            
    }
    String fileContent = sb.toString();
}

Upvotes: 1

Tamás
Tamás

Reputation: 398

You can use a URLClassLoader to access resources in a JAR archive.

Upvotes: 0

Related Questions