Properties类概述
-
java.util.Properties(类):它实现了Map接口,所以它本质上是一个Map集合。它里面增加了一些方法,可以结合IO流,很方便地操作“配置文件”。
-
什么是配置文件:配置文件通常是用于记录软件运行时,用户的一些配置文件信息。它是“纯文本文档”。这种配置文件在国际上有一种“通用格式”:名=值。由于这种配置文件的格式跟Map的格式相同,所以用Map记录这种文件信息,非常适合。所以java制作了Properties类。
Properties类与流相关的方法介绍
1.构造方法:
Properties p = new Properties();
2.常用方法:
1).public Object setProperty(String key, String value); 相当于:put()
2).public String getProperty(String key): 相当于get()
3).public Set<String> stringPropertyNames():相当于:keySet().
4).public void store(Writer out,String str):向配置写入集合的键值对。
5).public void load(Reader in,String str);从配置文件读取。
3.实例代码
public class Test01 {
public static void main(String[] args) {
propertiesReadFile();
}
private static void propertiesWriteToFile(){
//1.创建Properties对象
Properties properties = new Properties();
//2.存数据
properties.setProperty("maGogal1", "张三");
properties.setProperty("maGogal2", "张四");
properties.setProperty("maGogal3", "张五");
properties.setProperty("maGogal4", "张6");
//3.写入到文件
try (FileWriter fileWriter = new FileWriter("demo05.txt")) {
properties.store(fileWriter, null);//第二个参数是生成文件的注释
} catch (IOException e) {
e.printStackTrace();
}
}
private static void propertiesReadFile(){
//1.创建Properties
Properties properties = new Properties();
//
try (FileReader reader = new FileReader("demo05.txt")) {
properties.load(reader);//会将配置文件中的键值对一次性的读取到集合中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Set<String> strings = properties.stringPropertyNames();
for (String s : strings) {
System.out.println(s + " , " + properties.getProperty(s));
}
}
}