[英]Reading a java properties file using input Stream
我在使用InputStream和類Loader函數時遇到空指針異常,但是在使用FileInputStream時,它正在正確讀取屬性文件。
為什么我收到此錯誤? 下面是我的代碼。
public String readProperties()
{
String result = "";
Properties prop = new Properties();
String file = "test.properties";
//InputStream fins = getClass().getClassLoader().getResourceAsStream(file);
try
{
prop.load(new FileInputStream(file));
//prop.load(fins);
}
catch (IOException e) {
e.printStackTrace();
}
String nation = prop.getProperty("Nation");
String city = prop.getProperty("City");
String state = prop.getProperty("State");
result = "I live in "+city+" in "+state+" in "+nation;
return result;
}
確保將test.properties文件保留在classpath中:即,在應用程序的Src文件夾中
這是示例代碼:
package com.example;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ReadProperties {
public static void main(String[] args) {
ReadProperties r = new ReadProperties();
String result = r.readProperties();
System.out.println("Result : " + result);
}
public String readProperties()
{
String result = "";
Properties prop = new Properties();
String file = "test.properties";
InputStream fins = getClass().getClassLoader().getResourceAsStream(file);
try
{
//prop.load(new FileInputStream(file));
if(fins!=null)
prop.load(fins);
}
catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
String nation = prop.getProperty("Nation");
String city = prop.getProperty("City");
String state = prop.getProperty("State");
result = "I live in "+city+" in "+state+" in "+nation;
return result;
}
}
在您的情況下, getResourceAsStream
-method將在您的類的包中搜索。
從ClassLoad.getResource
:
此方法將首先在父類加載器中搜索資源; 如果父級為null,則搜索虛擬機內置的類加載器的路徑。 失敗的話,此方法將調用findResource(String)來查找資源。
這些ClassLoader
方法用於搜索可能捆綁的Java應用程序(例如,jar文件),而不用於搜索應用程序旁邊的文件,這似乎是您在這種情況下想要做的。 請參見ClassLoader JavaDoc 。
如果ClassLoader
無法找到資源,則getResource*
方法將返回null
,因此您的代碼將失敗( NullPointerException
> stream為null
)。
更新:如果properties文件位於項目的根目錄中,則在使用ClassLoader時,可以在路徑的開頭使用/
進行嘗試。 有關更多信息,請參見此線程 。
代碼可能像這樣:
String file = "/test.properties";
InputStream fins = getClass().getResourceAsStream(file);
InputStream fins = MyClass.class.getResourceAsStream(file);
相對於getClass()
的類尋求資源,但是以/
開頭使其絕對。 但是,使用getClass()
意味着實際的類可能來自另一個jar,因此使用實際的類名可能會更好。
與使用File相比,可能從jar(zip格式)中獲取資源。 由於Windows上的File不區分大小寫,因此可以在Windows上使用File而不是作為資源或其他平台(Linux,MacOSX)使用Test.properties。
打開罐子(zip)並檢查是否存在test.properties
。
為了完整起見:您還可以使用ClassLoader來獲取資源。 跨罐這很好。 但是,該路徑必須是絕對路徑,而不是以/
開頭。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.