JAVA属性加载静态变量inputstream返回空值

标签 java

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/

相关文章:

java - 替换两个引号

java - 将字节数组显示为位图以在 Android 中获取图像的问题

java - 排除 JAXB 中的字段

java - Spring JSON序列化、Gson反序列化

java - Selenium 网络驱动程序 : How many times does a driver try to find element with an implicit wait timeout?

java - DefaultTableModel 不刷新

java - 高峰期求解器遇到无限循环任何不平凡的难题

java - 基于逻辑构造对象类型——这可以做到吗?

java - 如何将二维数组乘以因子

使用 Selenium 的 Java 和 Tor 浏览器