public class PropertyDemo {
private static InputStream in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
public void test() {
try {
// InputStream in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
Properties pro = new Properties();
pro.load(in);
String address = pro.getProperty("returnInfoRegister");
System.out.println(address);
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PropertyDemo().test();
new PropertyDemo().test();
}}
在上面的代码中,第一次运行将返回正确的值,但第二次运行返回空值我不知道为什么,但是当我将“in”变量更改为非静态(我的意思是局部变量)时,事情进展顺利,但为什么?
最佳答案
当您在流中移动并阅读它时,您就到达了它的末尾。使用它作为静态变量,保存该状态(因为它是您在 main 中声明的两个类实例中的同一变量)。因此,下次使用它时,它已经位于流的末尾。当您将其声明为非静态时,它是每个类实例的一个新实例,这样就很好了。
但是确实没有理由将其声明为类级别变量。你的内部变量要好得多。您还应该考虑在最后关闭流。
public class PropertyDemo {
//private static InputStream in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
public void test() {
InputStream in = null;
try {
in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
Properties pro = new Properties();
pro.load(in);
String address = pro.getProperty("returnInfoRegister");
System.out.println(address);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (in != null) {
try {in.close();} catch (Exception e) {}
}
}
}
public static void main(String[] args) {
new PropertyDemo().test();
new PropertyDemo().test();
}
}
关于JAVA属性加载静态变量inputstream返回空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37769856/