使用输入流读取java属性文件
我在使用InputStream和类加载器函数时遇到空指针异常,但在使用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;
}
# 1 楼答案
在您的案例中,
getResourceAsStream
-方法将在类的包中进行搜索从
ClassLoad.getResource
这些
ClassLoader
方法用于搜索可能捆绑的java应用程序(例如,作为jar文件),而不是搜索应用程序旁边的文件,这似乎是您在本例中想要做的事情。见ClassLoader JavaDoc如果
ClassLoader
无法找到资源,getResource*
-方法将返回null
,因此代码将失败(NullPointerException
->;流为null
)更新:如果属性文件位于项目的根目录中,则在使用类加载器时,可以在路径开头使用
/
来尝试。详见this thread