我在使用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;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
确保将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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15216 次 |
| 最近记录: |