版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40178464/article/details/82082268
Properties集合:基于Hashtable,该集合中的键值对都是字符串类型,集合中的数据类型可以保存到流中,或者从流中获取,该集合是线程安全的。
1.应用场景:通常该集合用于操作以键值对形式存在的配置文件。
2.存储/修改:setProperty()
3.获取:利用Set集合的获取,Set< String> s = 对象.stringPropertyNames()
4.调试用方法:对象.list(System.out),打印集合中所有的内容
5.持久化方法:store(),此方法需要关联输出流,例:
Properties pro = new Properties();
FileOutputStream fos = new FileOutputStream("目标文件");
pro.store(fos,"注释信息");
fos.close();
注:注释信息应避免中文
6.数据加载:load(),将文件中的数据加载到集合中,必须保证文件中的数据是以键值对形式存在的。例:
Properties pro = new Properties();
FileOutputStream fos = new FileOutputStream("目标文件");
pro.load(fos);
pro.list(System.out);
简单应用:
1.创建文件并将文件内容显示在控制台
public static void propertiesTest() {
//创建一个Properties集合。
Properties prop = new Properties();
//存储元素。
prop.setProperty("zhangsan", "30");
prop.setProperty("lisi", "31");
prop.setProperty("wangwu", "36");
prop.setProperty("zhaoliu", "20");
//取出所有元素。
Set<String> names = prop.stringPropertyNames();
for (String name : names) {
String value = prop.getProperty(name);
System.out.println(name + ":" + value);
}
//想要将这些集合中的字符串键值信息持久化存储到文件中需要关联输出流
FileOutputStream fos = new FileOutputStream("infodfd0.txt");
//将集合中数据存储到文件中,使用store方法,第二个参数为注释信息
prop.store(fos, "info");
fos.close();
}
控制台结果:
lisi:31
zhaoliu:20
zhangsan:30
wangwu:36
文件内容:
#info
#Sun Aug 26 16:55:22 GMT+08:00 2018
lisi=31
zhaoliu=20
zhangsan=30
wangwu=36
2.读取配置文件并修改
public static void test() throws IOException {
// 读取文件。
File file = new File("info.txt");
if (!file.exists()) {
throw new RuntimeException("读取失败");
}
FileReader fr = new FileReader(file);
// 创建集合存储配置信息。
Properties prop = new Properties();
// 将流中信息存储到集合中。
prop.load(fr);
// 修改信息
prop.setProperty("wangwu", "16");
FileWriter fw = new FileWriter(file);
prop.store(fw, "new info");
// 打印到控制台
prop.list(System.out);
fw.close();
fr.close();
}
控制台结果:
-- listing properties --
lisi=31
zhaoliu=20
zhangsan=30
wangwu=16
文件内容:
#new info
#Sun Aug 26 17:03:57 GMT+08:00 2018
lisi=31
zhaoliu=20
zhangsan=30
wangwu=16
Properties集合在以后的web中应用广泛,是一个较为重要的内容。