簡體   English   中英

jython從jar文件讀取文件

[英]jython reading file from jar file

我的jar / zip文件包含位於classes文件夾下的名為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)

您無法使用FileInputStream來訪問JAR中的文件(如普通文件)。 相反,您需要使用Class.getResourceAsStream()作為資源來訪問它們。 嘗試這樣的事情:

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

我很高興您能夠弄清楚如何調用getResourceStream。 我不確定“標記為無效”錯誤的含義。 這對我來說很好:

    $ 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! ,以上是我的預期輸出。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM