Java持久化存储对象Properties的方法list、store、load

package FileDemo;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Properties;

public class PropertiesFunctions {

    /**
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {

        /*
         * Map |--Hashtable |--Properties:
         * 
         * Properties集合: 特点: 1,该集合中的键和值都是字符串类型。 2,集合中的数据可以保存到流中,或者从流获取。
         * 
         * 通常该集合用于操作以键值对形式存在的配置文件。
         */
        test();
        myLoad();
        method_1();
        method_2();

    }

    private static void method_2() {//Property集合的简单使用
        Properties prop=new Properties();
        prop=System.getProperties();
        prop.list(System.out);
    }

    private static void method_1() throws IOException {// Store方法演示
        Properties prop = new Properties();
        prop.setProperty("wangwu", "12");
        prop.setProperty("ciugwu", "25");
        prop.setProperty("zhangsan", "32");
        prop.setProperty("liuxiao", "36");
        FileOutputStream fos = new FileOutputStream("D:\info1.txt");
        prop.store(fos, "info");
        fos.close();
    }

    private static void myLoad() throws IOException {// 模拟Property集合的load方法
        Properties prop = new Properties();
        BufferedReader bufr = new BufferedReader(new FileReader("D:\info.txt"));
        String line = null;
        while ((line = bufr.readLine()) != null) {
            if (line.startsWith("#")) {
                continue;
            }
            String arr[] = line.split("=");
            prop.setProperty(arr[0], arr[1]);
        }
        prop.list(System.out);
        bufr.close();
    }

    private static void test() throws IOException {
        // 对已有的配置文件中的信息进行修改。
        /*
         * 读取这个文件。 并将这个文件中的键值数据存储到集合中。 在通过集合对数据进行修改。 在通过流将修改后的数据存储到文件中。
         */
        File file = new File("D:\info.txt");
        if (!file.exists()) {
            file.createNewFile();
        }
        FileReader fr = new FileReader(file);
        // 创建集合存储配置信息
        Properties prop = new Properties();
        prop.load(fr);
        prop.setProperty("wangwu", "16");
        FileWriter fw = new FileWriter(file);
        prop.store(fw, "");
        prop.list(System.out);
        fw.close();
        fr.close();
    }

}
原文地址:https://www.cnblogs.com/ysw-go/p/5300620.html