2017-03-01 102 views
-1

我有有代碼現在如何讀取屬性從不同的位置,文件中JAVA

public class SourceHandler { 
    String PrpPath = null; 
    Properties prop = null; 

public Properties loadConfigProperties() { 

try { 

    System.out.println("Propertiess " +PrpPath); 
    InputStream in =new FileInputStream(new File(PrpPath)); 
    prop.load(in); 

} catch (FileNotFoundException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 
return prop; 
} 

,並在不同類的主要方法,

public static void main(String[] args) throws ParserConfigurationException, 
               Exception { 
    try { 

     SourceHandler conf = new SourceHandler(); 

     conf.setProperties("C:/config.properties"); 

     Properties p = conf.loadConfigProperties(); 

     System.out.println("Done"); 

    } catch (DOMException dome) { 
     // TODO: Add catch code 
     dome.printStackTrace(); 
    } 

,如果我跑sourcehandler.java類的代碼,它示出了在線路零指示字例外,prop.load(in);

堆棧跟蹤:

顯示java.lang.NullPointerException 在DecryptEncryptSource.SourceHandler.loadConfigProperties(SourceHandler.java:98) 在DecryptEncryptSource.SourceHandler.updateCofigDestn(SourceHandler.java:151) 在DecryptEncryptSource.MainClass.main(MainClass.java:27)

+0

您可以加入的確切路徑'字符串'你在用嗎? – Berger

+0

是Berger,這是從主要方法傳遞的確切路徑「C:\ config.properties」,我也可以通過sop打印。 – Jeelan

+0

向我們展示如何從'main'方法傳遞它,這是至關重要的。 –

回答

0

首先,

InputStream in =new FileInputStream(new File(Properties)); 

應該更好地閱讀

InputStream in =new FileInputStream(new File(propertyFileName)); 

以避免任何歧義;然後:

  • 你確定真的是有一個名爲C:\config.properties
  • 也許你需要或者逃避文件:C:\\config.properties;或者您嘗試C:/config.properties

關於更新;你有這樣一行:

Properties prop = null; 

進一步回落:

prop.load(in); 

你感到吃驚的是,你得到一個NPE?真?提示:看看你的代碼和創建 Property對象使用文件路徑;而不是僅僅調用一個空對象的方法。

真正的答案是一遍又一遍地讀出here

(併爲那些誰不知道爲什麼我沒有收出的重複......我不能更多,因爲我已經接近請求的另一個原因)

+0

我有該文件的路徑C:\\ config.properties,現在在線,prop.load(in);它會拋出java.lang.NullPointerException異常 – Jeelan

+0

請看現在的問題是增強的... – Jeelan

+0

謝謝鬼貓,它是我愚蠢的錯誤.. – Jeelan