歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Java 配置信息類 Properties 的簡單使用

Java 配置信息類 Properties 的簡單使用

日期:2017/3/1 9:08:31   编辑:Linux編程

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:1101
name:lisi    id:1104
name:小二    id:1102
name:張3    id:1103

相關方法:

構造方法:Properties();//無默認值

     Properties(Properties defaults);  //指定默認值

配置信息:setProperties(key,value);  //鍵值都是字符串類型

寫入數據:(1)store(new FileWriter("C:\\.."),"配置信息的描述語") ;  //如果需要寫入中文時建議使用字符流

     (2)store(new FileOutputStream(C:\\..),"配置信息的描述語");  // 字節流

讀取數據: load(new FileReader("C:\\.."));  //字符流讀取

Copyright © Linux教程網 All Rights Reserved