Java-复习-Properties集合-IO流-简单复习

一、 Properties集合简单复习:

1、Properties集合是Hashtable的子类,双列集合,Properties 是唯一一个与IO流相交互的集合,Properties 类表示了一个持久的属性集

2、常用方法:

public  Object setProperty(String k,String v): 保存一个键值对(属性名=属性值)
public  String getProperty(String key): 根据属性名获取属性值
public Set<String> stringPropertyNames(): 获取所有属性值对应的Set集合

示例代码

public class PropertiesExercise {
    public static void main(String[] args) {
        //创建properties集合对象
        Properties pts = new Properties();
        //保存一个键值对
        pts.setProperty("user", "root");
        pts.setProperty("passWord", "000000");
        //获取集合中的所有键值对的键的Set集合
        Set<String> keys = pts.stringPropertyNames();
        //遍历
        for (String key : keys) {
            //获取键对应的值
            String value = pts.getProperty(key);
            System.out.println(key + "::" + value);
        }
    }
}

扩展:使用java.lang.System类的静态方法getProperties()获取系统相关属性值

public static Properties getProperties(): 获取系统相关的属性名及属性值

二、Properties集合与IO的简单交互示例

将config.properties文件中的age + 2

age=18
name=tom
email=tom@163.com
gener=man

示例代码:

public class PropertiesExercise02 {
    public static void main(String[] args) throws IOException {
        //创建properties集合对象
        Properties pts = new Properties();
        //创建InputStream/Reader的子类对象,绑定源文件
        FileInputStream fis = new FileInputStream("A\\src\\config.properties");
        //properties集合的load方法将文件内容以键值对的方式加载到集合中
        pts.load(fis);
        //释放资源
        fis.close();
        //获取集合中的键的Set集合
        Set<String> propertyNames = pts.stringPropertyNames();
        //遍历
        for (String propertyName : propertyNames) {
            //如果键是age
            if ("age".equals(propertyName)) {
                //替换值,值的参数为String,先将值获取到,使用Integer转换,进行+2,最后+"",转回String
                pts.setProperty("age", Integer.parseInt(pts.getProperty(propertyName)) + 2 + "");
            }
        }
        //将Properties集合中的内容重新存储到config.properties文件中
        FileOutputStream fos = new FileOutputStream("A\\src\\config.properties\\");
        //store方法内部会将pts中的内容重新存储到.properties文件中
        //config.properties文件会被重写
        pts.store(fos, null);
    }
}

更改成功

#Mon Aug 15 20:56:39 CST 2022
age=20
email=tom@163.com
name=tom
gener=man

版权声明:本文为koga_原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。