StarSky StarSky - 5 months ago 30
Java Question

JAVA Property load static variable inputstream return null value

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 above code the first run will return correct value but the second run return null value I don't know why ,but when I change "in" variable to non static (I mean a local variable) things goes right but why?

Answer

When you move through the stream reading it, you are at the end of it. Using this as a static, saves that state (as it is the same variable in both class instances you have declared in main). So the next time you use it, it is already at the end of the stream. When you declare it as non-static, it is a new instance for each class instance and you are good.

But there really is no reason to declare this as a class level variable. Your inner variable is much better. You should also consider closing the stream at the end.

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();
    }
}
Comments