Properties类与IO的结合

Properties这个类是Map集合的子类。它的父类Hashtable。但是这个类可以流进行结合,可以把集合中的数据直接保存到文件中,或者和流结合,直接把文件中的数据读取后,直接放在集合中。

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.Set;

import javax.swing.text.html.HTMLDocument.Iterator;
public class IoDemo {
    public static void main(String[] args) throws IOException {
        
        read();
    }
    
    public static void read() throws IOException {
        Properties prop = new Properties();
        FileInputStream fis = new FileInputStream("e:/prop.txt");
        prop.load(fis);
        Set set = prop.keySet();
        for (java.util.Iterator it = set.iterator(); it.hasNext();) {
            Object key = it.next();
            Object value = prop.get(key);
            System.out.println(key + "...." + value);
        }
        fis.close();
    }
    
    public static void save() throws IOException {
        // 创建Properties对象
        Properties prop = new Properties();
        // 给集合中存放数据
        prop.setProperty("zhangsan", "shanghai");
        prop.setProperty("lisi", "beijing");
        prop.setProperty("wangwu", "wuhan");
        prop.setProperty("zhaoliu", "shenzhen");
        
        FileOutputStream out = new FileOutputStream("e:/prop.txt");
        prop.store(out, "lishuai");
        out.close();
    }
}

推荐阅读更多精彩内容