从jar文件中读取jython文件

时间:2014-05-08 23:02:34

标签: java python jython

我的jar / zip文件包含类文件夹下名为accord.properties的属性文件。

Zip/Jar file:
  +classes
      +accord.properties

我正在阅读文件:

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)

在Tomcat服务器上运行时,我收到错误

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)

尝试

pFile = loadPropsFil("accord.properties")

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

同样的错误。

修改

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

这里inStream给出null并导致NullPointer异常。

错误:

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

1 个答案:

答案 0 :(得分:1)

您无法使用FileInputStream访问JAR中的文件,例如普通文件。相反,您需要使用Class.getResourceAsStream()资源的形式访问它们。尝试这样的事情:

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

我很高兴您能够弄清楚如何调用getResourceStream。我不确定“Mark invalid”错误是什么意思。这对我来说很好:

    $ 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!'

由于hello.jar包含具有单行hello.txt的文件Hello!,因此以上是我的预期输出。