1.Properties类概述
Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置文件中很多变量是经常改变的,这样做也是为了方便用户,让用户能够脱离程序本身去修改相关的变量设置。
在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
Properties类继承自,如下
- Properties类特点:
-
Hashtable 的子类,map 集合中的方法都可以用。
-
该集合没有泛型,键值都是字符串。
-
它是一个可以持久化的属性集,具有和IO流技术相结合的方法。
2.Properties类使用
- Properties 集合常见方法
调用Hashtable的方法put。他通过调用基类的put方法来设置 键 - 值对
public synchronized Object setProperty(String key, String value);
用指定的键在此属性列表中搜索属性。也就是通过参数 key,得到key 所对应的value。
public String getProperty(String key);
获取properties属性列表中所有的key值,并返回一个set类型的集合。
public Set<String> stringPropertyNames();
将properties属性列表输出到指定的输出流。
public void list(PrintStream out);
【示例】向 Properties 集合中添加元素,并遍历
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
// 创建一个Properties对象
Properties properties = new Properties();
// 添加元素
properties.setProperty("zhangsan", "18");
properties.setProperty("lisi", "28");
properties.setProperty("wangwu", "38");
properties.setProperty("zhaoliu", "48");
// 更改元素值
properties.setProperty("wangwu", "20");
// 遍历所有元素
// 获取Properties对象的所有的key值
Set<String> names = properties.stringPropertyNames();
for (String name : names) {
// 根据key获取value值
String value = properties.getProperty(name);
System.out.println(name + " : " + value);
}
}
}
3.Properties类&IO流
- 将集合中内容存储到文件
将此属性列表(键和元素对)写入此 Properties表中,以适合于使用InputStream方法加载到 Properties表中的格式输出流。
public void store(Writer writer, String comments);
将此属性列表(键和元素对)写入此 Properties表中,以适合使用Reader方法的格式输出到输出字符流。
public void store(OutputStream out, String comments);
【示例】将 Properties 集合中的元素存储到文件中
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
// 创建一个Properties集合
Properties properties = new Properties();
// 添加元素
properties.setProperty("zhangsan", "18");
properties.setProperty("lisi", "28");
properties.setProperty("wangwu", "38");
properties.setProperty("zhaoliu", "48");
// 创建字节输出流
FileOutputStream fos = new FileOutputStream("info.txt");
// 对properties集合进行持久化操作,参数二为对配置文件的描述
properties.store(fos, "name+age");
fos.close();
}
}
- 读取配置文件中的数据
从输入字符流中读取属性列表(键和元素对)。
public synchronized void load(Reader reader);
从输入字节流读中取属性列表(键和元素对)。
public synchronized void load(InputStream inStream);
【示例】读取文件中的数据,并保存到集合
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
// 创建一个Properties对象
Properties properties = new Properties();
// 读取配置文件中的信息
properties.load(new FileInputStream("info.txt"));
// 输出属性列表的内容
properties.list(System.out);
}
}
【示例】对配置文件中的数据进行修改
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
// 创建一个Properties对象
Properties properties = new Properties();
// 读取配置文件中的数据
properties.load(new FileInputStream("info.txt"));
// 对properties的数据进行修改
properties.setProperty("zhaoliu", "10");
// 对properties进行持久化操作
properties.store(new FileOutputStream("info.txt"), "name+age");
}
}
ps:如需最新的免费文档资料和教学视频,请添加QQ群(627407545)领取。