AKB
AKB

Reputation: 5938

jython reading file from jar file

I have jar/zip file contains properties file called accord.properties under classes folder.

Zip/Jar file:
  +classes
      +accord.properties

I am reading file as:

from java.util import Properties
from java.io import File, FileInputStream
def loadPropsFil(propsFil):
    print(propsFil)    
    inStream = FileInputStream(propsFil)
    propFil = Properties()
    propFil.load(inStream) 
    return propFil
pFile = loadPropsFil("/accord.properties")
print(pFile)

while running in Tomcat server, I am getting error as

Exception stack is: 1. accord.properties (No such file or directory) (java.io.FileNotFoundException) java.io.FileInputStream:-2 (null) 
2. null(org.python.core.PyException) org.python.core.Py:512 (null) 
3. java.io.FileNotFoundException: java.io.FileNotFoundException: accord.properties (No such file or directory) in <script> at line number 34 (javax.script.ScriptException)

Tried with

pFile = loadPropsFil("accord.properties")

and

pFile = loadPropsFil("classpath:accord.properties")

same error.

EDIT

inStream = ClassLoader.getSystemClassLoader().getResourceAsStream("accord.properties")
strProp = Properties().load(inStream) # line 38
options.outputfile=strProp.getProperty("OUTPUT_DIR")

Here inStream gives null and causes NullPointer Exception.

Error:

 java.lang.NullPointerException: java.lang.NullPointerException in <script> at line number 38 (javax.script.ScriptException)

Upvotes: 0

Views: 859

Answers (1)

DaoWen
DaoWen

Reputation: 33019

You can't access files in a JAR like a normal file using FileInputStream. Instead, you need to access them as resources using Class.getResourceAsStream(). Try something like this:

inStream = ClassLoader.getSystemClassLoader().getResourceAsStream("accord.properties")

I'm glad you were able to figure out how to call getResourceStream. I'm not sure what the "Mark invalid" error means. This works fine for me:

    $ CLASSPATH=hello.jar:$CLASSPATH jython
    Jython 2.5.3 (2.5:c56500f08d34+, Aug 13 2012, 14:48:36)
    [Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.8.0
    Type "help", "copyright", "credits" or "license" for more information.
    >>> from java.lang import ClassLoader
    >>> from java.io import InputStreamReader, BufferedReader
    >>> inStream = ClassLoader.getSystemClassLoader().getResourceAsStream("hello.txt")
    >>> reader = BufferedReader(InputStreamReader(inStream))
    >>> reader.readLine()
    u'Hello!'

Since hello.jar contains the file hello.txt which has the single line Hello!, the above is my expected output.

Upvotes: 1

Related Questions