我在使用 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 文件保存在类路径中:即在应用程序的 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;
}
}
关于java - 使用输入流读取 java 属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26967352/