java Properties 配置信息类

时间:2023-03-09 04:58:05
java Properties 配置信息类

Properties(配置信息类):主要用于生产配置文件和读取配置文件信息。

----> 是一个集合类 继承HashTable 存值是以键-值的方式。

package com.beiwo.io;

import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set; public class demo5 { public static void main(String[] args) throws IOException {
// 调用方法
creatPeoperties();
readPeoperties();
} }

写入配置信息方法:

    public static void creatPeoperties() throws IOException {
// 创建properties对象
Properties properties = new Properties();
// 配置信息 键 和值都是字符串
properties.setProperty("张三", "123");
properties.setProperty("李四", "234");
properties.setProperty("王五", "345");
properties.setProperty("赵六", "456");
properties.setProperty("宋七", "567"); // 将配置信息写入磁盘中
properties.store(new FileWriter("C:\\Users\\cdlx2016\\Desktop\\2\\User.properties"), "这是用户配置信息"); }

读取配置的信息

    public static void readPeoperties() throws IOException, IOException {
// 创建peoperties对象
Properties properties = new Properties();
properties.load(new FileReader("C:\\Users\\cdlx2016\\Desktop\\2\\User.properties")); // 遍历配置信息
Set<Entry<Object, Object>> entrys = properties.entrySet();
for (Entry<Object, Object> entry : entrys) {
System.out.println("key: " + entry.getKey() + " -- value: " + entry.getValue());
} }