Welcome 微信登录

首页 / 操作系统 / Linux / Java 配置信息类 Properties 的简单使用

Properties :(配置信息类) 是一个表示持久性的集合 ,继承 Hashtable ,存值是以键-值得方式
主要用于生产配置文件和读取配置文件信息。简单的实例:import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;public class properties {    public static void main(String[] args) throws IOException {
        createPropert();
        readPropert();
    }
   
    //(一)创建配置信息类
    public static void  createPropert() throws IOException {
        //1.创建对象
        Properties pt = new Properties();
       
        //2.配置对象信息(键值都是字符串类型)
        pt.setProperty("初一", "1101");
        pt.setProperty("小二", "1102");
        pt.setProperty("张3", "1103");
        pt.setProperty("lisi", "1104");
       
        //3.将配置好的对象文件存入磁盘(两个方法都可以)
        //(1)store(new FileWriter("C:\.."))        如果需要写入中文时建议使用字符流
        //(2)store(new FileOutputStream(C:\..))    字节流
        pt.store(new FileWriter("C:\Users\bigerf\Desktop\配置流.properties"), "这是对文件的描述信息:");
    }
   
   
    //(二)读取配置对象的信息
    public static void  readPropert() throws FileNotFoundException, IOException {
        //1.创建对象
        Properties pt = new Properties();
       
        //2.根据路径 读取配置对象数据 load(new FileReader("C:\.."))
        pt.load(new FileReader("C:\Users\bigerf\Desktop\配置流.properties"));
       
        //3.遍历集合(配置对象数据) 
        //集合是可以通过foreach循环来遍历的
        Set<Entry<Object, Object>> entrys = pt.entrySet();
        for (Entry<Object, Object> entry : entrys) {
            System.out.println("name:"+entry.getKey() +"    id:"+ entry.getValue());
        }
    }
}打印结果:name:初一id:1101name:lisiid:1104name:小二id:1102name:张3id:1103相关方法:构造方法:Properties();//无默认值 Properties(Properties defaults); //指定默认值配置信息:setProperties(key,value); //键值都是字符串类型写入数据:(1)store(new FileWriter("C:\.."),"配置信息的描述语") ; //如果需要写入中文时建议使用字符流 (2)store(new FileOutputStream(C:\..),"配置信息的描述语"); // 字节流读取数据: load(new FileReader("C:\..")); //字符流读取本文永久更新链接地址:http://www.linuxidc.com/Linux/2016-12/138056.htm