2016-10-19 101 views
1

我有一個屬性文件,名字是XYZ.properties。我想從這個文件中獲取詳細信息。 我的屬性文件位置是D:\properties_file\XYZ.propertiesJava加載屬性文件java.lang.NullPointerException錯誤

對於這個我使用下面的代碼

import java.io.InputStream; 
import java.util.Properties; 

public class LoadProp { 
    private static Properties prop = new Properties(); 
    public static Properties getProperties() throws Exception { 
     if (prop.isEmpty()) { 
      InputStream fis = LoadProp.class.getResourceAsStream("D:\\properties_file\\XYZ.properties"); 
      prop.load(fis); 
     } 
     return prop; 
    } 
} 

public class demo extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    private static Properties propFile; 

    public void doPost(HttpServletRequest request, HttpServletResponse response) { 
     try { 
      propFile = LoadProp.getProperties(); 
      System.out.println(propFile.getProperty(Constants.URL)); 
     } 
     catch (ServletException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (Exception e1) { 
      e1.printStackTrace(); 
     } 
    } 
} 

但是,當我在prop.load(fis)線運行這個它給了我下面的錯誤

java.lang.NullPointerException 
+0

資源不是文件,不駐留在文件系統中,沒有反斜槓作爲目錄分隔符,也沒有驅動器號作爲其名稱的一部分。 – EJP

回答

1

改變這一行:

InputStream fis = LoadProp.class.getResourceAsStream("D:\\properties_file\\XYZ.properties"); 

to

InputStream fis = new FileInputStream("D:\\properties_file\\XYZ.properties"); 

getResourceAsStream被設計來讀取classpath中(應用內的資源)的資源,以讀取文件,它是應用程序之外,使用Java文件API。

+1

好心解釋downvote? –

+1

我不是下來的選民,但「來自classpath的資源」而不是「你的應用程序內的資源」將更合適。 –

0

Class.getResourceAsStream不打開文件系統位置。它試圖在類路徑中找到資源。您可能需要改爲使用FileInputStream來閱讀屬性。