Properties与IO流的搭配使用

Properties的Load() 读取硬盘的数据

/* 可以使用Properties集合中的方法Load,把硬盘中保存的文件(键值对),读取到集合中使用
void load( Reader reader)
参数:
    InputStream inStream:字节输入流,不能读取含有中文的键值对Reader reader:字符输入流,能读取含有中文的键值对
使用步骤:
    1.创建Properties集合对象
    2.使用Properties集合对象中的方法Load读取保存键值对的文件
    3.遍历Properties集合
注意:
	1.存储键值对的文件中,键与值默认的连接符号可以使用=,空格(其他符号)
    2.存储键值对的文件中,可以使用#进行注释,被注释的键值对不会再被读取
    3.存储键值对的文件中键与值黑默认都是字符串,不用再加引号
*/
   
public static void main(String[] args)throws IOException {
    
    
    Properties properties = new Properties();
        FileReader r = new FileReader("D:\\ABC\\a.txt");
        properties.load(r);
        Set<String> set =properties.stringPropertyNames();
        for (String s:set) {
    
    
            String name = properties.getProperty(s);
            System.out.println(s+"__"+name);
        }
}
//输出结果a.txt中的内容
	a__111
	b__222

Properties的store() 写入硬盘的数据

/*可以使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储
    
void store(writer writer,string comments)
    参数:
        Outputstream out:字节输出流,不能写入中文writer writer:字符输出流,可以写中文
        String comments :注释,用来解释说明保存的文件是做什么用的不能使用中文,会产生乱码,认是unicode编码一般使用""
使用步骤:
        1.创建Properties集合对象,添加数据
        2.创建字节输出流/字符输出流对象,构造方法中绑定要输出的目的地
        3.使用Properties集合中的方法store,把集合中的临时数据,持久化写入到硬盘中存储4.释放资源
*/
public static void main(String[] args)throws IOException {
    
    
     Properties properties = new Properties();
        properties.setProperty("a","111");
        properties.setProperty("b","222");
        properties.setProperty("c","333");
      //创建字符输出流
      FileWriter f = new FileWriter("D:\\ABC\\a.txt");
      properties.store(f,"this is message");
      f.close();
}

这里说明一下,使用字符流和字节流都可以实现功能,但是使用字节流碰到汉字会乱码。

简单说一下properties的常用方法

Properties的常用方法:
1.setProperty(String key, String value)
调用 Hashtable 的方法 put。
2.getProperty(String key)
用指定的键在此属性列表中搜索属性
3.getProperty(String key, String defaultValue)
用指定的键在属性列表中搜索属性。
4.load(InputStream inStream)
从输入流中读取属性列表(键和元素对)。
5.load(Reader reader)
按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
6.loadFromXML(InputStream in)
将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。
7.store(OutputStream out, String comments)
以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。
8.store(Writer writer, String comments)
以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。
9.storeToXML(OutputStream os, String comment)
发出一个表示此表中包含的所有属性的 XML 文档。
10.storeToXML(OutputStream os, String comment, String encoding)

猜你喜欢

转载自blog.csdn.net/weixin_45894479/article/details/115022813