请看代码,为什么第一次可以读取到但第二次读取时返回null值?
如果将in变量作为一个局部变量两次都可以读取到值,这是为什么?
public class PropertyDemo {
private static InputStream in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
public void test() {
try {
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();
}
}
一般的输入流都是只能读取一遍(可理解文件指针向前,不能回退,有个特殊:java.io.PushbackInputStream,可以看jdk文档),
有些InputStream的实现支持mark 和reset方法,这样可以重复从头读取;但是文件输入流应该是不支持的。你可以测试一下
静态的话只是在加载类的时候读一遍,用了的话后面不读了,局部变量每次调用都读一遍
import java.io.InputStream;
import java.util.Properties;
public class PropertyDemo {
private static InputStream in = PropertyDemo.class.getClassLoader().getResourceAsStream("address.properties");
static {
System.out.println(in.getClass());//class java.io.BufferedInputStream
System.out.println(in.markSupported());//true
in.mark(Integer.MAX_VALUE);
}
public void test() {
try {
Properties pro = new Properties();
pro.load(in);
String address = pro.getProperty("returnInfoRegister");
System.out.println(address);
in.reset();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
new PropertyDemo().test();
new PropertyDemo().test();
}
}