JAVA单排日记-2020/1/27-Properties集合

1.概述

  1. PropertiesHashtable<k,v>的子类,Hashtable<k,v>Map<k,v>接口的实现类
Properties extends Hashtable<k.v> implements Map<k,v>
  1. Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。
     ● Properties 集合是唯一一个和IO流结合的集合
     ● store()方法,把集合中的临时数据,持久化写入到硬盘中
     ● load()方法,把硬盘中保存的文件(键值对),读取到集合中使用
  2. Properties 集合是一个双列集合,键和值默认都是字符串

2.常用专属方法

1.添加数据

对象.setProperty(String key,String value)

2.通过键找到值

对象.getProperty(String key)

3.把Properties集合中的键取出,放入到一个set集合中

Set<String> set = 对象.stringPropertyNames();

3.store方法

store(OutputStream out,String comments)
store(Writer writer,String comments)

OutputStream out 输出字节流,不能写入中文
Writer writer 输出字符流,可以写中文
String comments 注释,用来解释保存的文件是干什么用的,不能使用中文,一般使用""(空字符串)

  • 使用步骤
  1. 创建Properties集合对象,添加数据
  2. 创建字节/字符输出流对象,构造方法中绑定输出的目的地
  3. 使用store()方法,把集合中的临时数据,持久化的写入到硬盘
  4. 释放资源
package Demo01;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.util.Properties;

public class Demo01 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();
        FileWriter writer = new FileWriter("G:\\Java\\测试文件夹\\a.txt");

        properties.setProperty("1","张三");
        properties.setProperty("2","李四");
        properties.setProperty("3","王五");
        properties.setProperty("4","赵六");

        properties.store(writer,"save data");

        writer.close();
    }
}

在这里插入图片描述

4.load方法

load(InputStream out);
load(Reader reader);

OutputStream out 字节输入流,不能读含有中文的键值对
Reader reader 字符输入流,读含有中文的键值对

  • 使用步骤
  1. 创建Properties集合对象
  2. 使用load()方法,读取键值对文件
  3. 遍历Properties集合
  • 注意
  • 键值对文件中,键与值默认连接符为=,空格,或者其他
  • 键值对文件中,可以使用#注释,被注释以后不会被读取
  • 键值对文件中,键与值默认都是字符串
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;

public class Demo02 {
    public static void main(String[] args) throws IOException {
        Properties properties = new Properties();

        properties.load(new FileReader("G:\\Java\\测试文件夹\\b.txt"));

        for (String i:properties.stringPropertyNames()){
            System.out.println(properties.get(i));
        }
    }
}

在这里插入图片描述在这里插入图片描述

发布了103 篇原创文章 · 获赞 1 · 访问量 2645

猜你喜欢

转载自blog.csdn.net/wangzilong1995/article/details/104091403