2016-05-07 53 views
0

我在我的應用程序的類路徑中有屬性文件。在爲這個應用程序創建jar文件之前,沒有問題,但是當我創建jar文件並使用java -jar命令運行它時,它將返回null pointer exception。這裏是我的代碼來加載屬性:如何訪問jar文件中的文件?

private Properties loadProperties() { 
    Properties prop = new Properties(); 
    InputStream input = null; 

    try { 
     input = this.getClass().getResourceAsStream("./auth"); 
     prop.load(input); 
    } catch (IOException ex) { 
     ex.printStackTrace(); 
    } finally { 
     if (input != null) { 
      try { 
       input.close(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
     } 
    } 
    return prop; 
} 

我可以訪問jar文件中的屬性文件或它是不可能的嗎?

這裏是例外,我得到:

Exception in thread "main" java.lang.NullPointerException 
    at java.util.Properties$LineReader.readLine(Properties.java:434) 
    at java.util.Properties.load0(Properties.java:353) 
    at java.util.Properties.load(Properties.java:341) 
    at com.kadir.MyApp.loadProperties(MyApp.java:109) 
    at com.kadir.MyApp.<init>(MyApp.java:62) 
    at com.kadir.MyApp.main(MyApp.java:48) 

和線路108和109是這些:

input =this.getClass().getClassLoader().getResourceAsStream("auth"); 
    prop.load(input); 

還要說明一點:我開發我的應用程序在Windows,但在Linux上運行它,錯誤可能來自這個

+4

在這裏你去:http://stackoverflow.com/questions/5171957/access-file-in-jar-file –

+0

@RafaelOsipov我仍然收到空指針異常 – kadir

+0

什麼是堆棧跟蹤? –

回答

0

我不知道爲什麼它不工作的確切原因,但改變這兩條線

input = this.getClass().getResourceAsStream("auth"); 
prop.load(input); 

這些:

ClassLoader classloader = Thread.currentThread().getContextClassLoader(); 
input = classloader.getResourceAsStream("auth"); 
prop.load(input); 

使我的代碼工作