属性不能在读取InputStream后加载



代码:

Properties prop = new Properties();
FileInputStream fis = new FileInputStream("src/prop.txt");
//Read the content
byte[] bys = new byte[1024];
int len;
while((len=fis.read(bys))!=-1) {
System.out.println(new String(bys));
}
//Load the properties and print
prop.load(fis);
fis.close();
System.out.println(prop);

src/prop.txt格式如下:

city=LA
country=USA

它在prop中打印不出任何内容,这意味着prop是空的:

{}

但是如果我删除读取部分,prop可以加载为:

{country=USA, city=LA}

为什么读了prop.txt的内容后没有完成prop ?

读取流后,流指针指向流的末尾。之后,当prop.load()尝试从流中读取时,没有更多可用的内容。您必须在流上调用reset()才能再次读取它。

Properties prop = new Properties(); 
BufferedInputStream fis = new BufferedInputStream(new FileInputStream("src/prop.txt"));
fis.mark(fis.available())  //set marker at the begining

//Read the content
byte[] bys = new byte[1024];
int len;
while((len=fis.read(bys))!=-1) {
System.out.println(new String(bys));
}
fis.reset(); //reset the stream pointer to the begining
//Load the properties and print
prop.load(fis);
fis.close();
System.out.println(prop);

它在prop中打印不出任何内容,这意味着prop为空:

因为你已经通过while条件下的fis.read(bys)输入流fis中可用的数据(看看read​(byte[] b)实际做什么),当你将它加载到你的属性中时,什么也没有留下。

FileInputStream不是持久保存数据的类型;它更像是一个对象,它代表一个管道,一个连接到文件描述符,数据从文件流出,一个字节一个字节,只要你不断调用.read(..)

另外,请阅读Oracle文档:

FileInputStream用于读取原始字节流,如图像数据。对于读取字符流,可以考虑使用FileReader

最好使用ResourceBundle来加载属性文件。假设您正在使用maven,您可以将属性文件命名为application。目录"src/main/resources"然后使用下面的代码加载和使用:

ResourceBundle resourceBundle = ResourceBundle.getBundle("application");
String value = resourceBundle.getString("key");

更多细节请参考ResourceBundle的javadocs。

更多示例见https://mkyong.com/java/java-resourcebundle-example/或https://www.baeldung.com/java-resourcebundle

最新更新