mkrems
mkrems

Reputation: 555

Reading in a text file from a jar in Jython

I have a Jython code base and several text files in a jar archive. I am using a script to pack them all into one jar file for easy distribution. I would like to be able to read the text files from within the jar file. I have tried the import statement the command:

fin = java.lang.ClassLoader.getResourceAsStream('path to the text file inside the jar')

and it says 2 arguments are expected instead of 1 for the getResourceAsStream method. I have searched quite a bit but have not found a clear way to do this using Jython. Thanks.

Upvotes: 1

Views: 1963

Answers (2)

mzjn
mzjn

Reputation: 50947

You are invoking getResourceAsStream() on the class, not an instance. That's why there is an error message.

If you first create a classloader object and then use getResourceAsStream() on that object, it should work. Something like this:

from java.lang import ClassLoader
from java.io import InputStreamReader, BufferedReader

loader = ClassLoader.getSystemClassLoader()
stream = loader.getResourceAsStream("org/python/version.properties")
reader = BufferedReader(InputStreamReader(stream))

line = reader.readLine()
while line is not None:
    print line
    line = reader.readLine()

Output:

# Jython version information
jython.version=2.5.3
jython.major_version=2
jython.minor_version=5
jython.micro_version=3
jython.release_level=15
jython.release_serial=0
jython.build.date=Aug 13 2012
jython.build.time=14:48:36
jython.build.hg_branch=2.5
jython.build.hg_tag=
jython.build.hg_version=c56500f08d34+

The output shows the contents of the org/python/version.properties file inside jython.jar (which is on the classpath when the program runs).

Upvotes: 2

Michał Niklas
Michał Niklas

Reputation: 54302

Jars are simply zip files so you can use zipfile module. There is my example of reading version info from manifest file:

def get_ver(jar_file):
    zf = zipfile.ZipFile(jar_file, 'r')
    try:
        lst = zf.infolist()
        for zi in lst:
            fn = zi.filename
            if fn.lower().endswith('manifest.mf'):
                try:
                    manifest_txt = str(zf.read(zi.filename), encoding='utf8')
                except TypeError:
                    manifest_txt = zf.read(zi.filename)
                lines = manifest_txt.split('\n')
                for line in lines:
                    if 'Implementation-Version:' in line:
                        return line[23:].strip()
    finally:
        zf.close()

Upvotes: 3

Related Questions