public class ReadData {
public static String file;
public static String readValue(String key) {
Properties props = new Properties();
try {
InputStream in =ReadData.class.getResourceAsStream(file);
props.load(in);
String value = props.getProperty(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
有这样一个类,我想在调用静态方法之前指定file的值,但总是抛出空指针异常
比如 我在另一个类中使用
public void example(){
ReadData.file="D://data.properties";
System.out.println(ReadData.readValue("key"));
}
为什么抛空指针异常? 是静态类加载了吗?怎么解决?
------解决方案--------------------
public class ReadData {
public static String file = "d:/test.txt";;
public static String readValue(String key) {
Properties props = new Properties();
try {
InputStream in = ReadData.class.getResourceAsStream(file);
props.load(in);
String value = props.getProperty(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}
或者是
public class ReadData {
// public static String file;;
public static String readValue(String key,String file) {
Properties props = new Properties();
try {
InputStream in = ReadData.class.getResourceAsStream(file);
props.load(in);
String value = props.getProperty(key);
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
}