jython 从 jar 文件读取文件
我有一个jar/zip文件,里面有一个叫做accord.properties的属性文件,这个文件放在classes文件夹下。
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,导致了空指针异常。
错误信息:
java.lang.NullPointerException: java.lang.NullPointerException in <script> at line number 38 (javax.script.ScriptException)
1 个回答
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!
,所以我期待的输出就是这个。