屬性類 Properties
Properties 類本身是 HashTable 類的子類,數據存放也是按照key和value的形式存放數據的。
public class Properties extends HashTable<Object, Object>
Properties 類的主要方法:
- public Properties() //構造一個空的屬性類
- public Properties(Properties defaults) //構造一個指定屬性內容的類
- public String getProperty(String key) //根據屬性的key取得屬性的value,如果沒有key則返回null
- public String getProperty(String key, String defaultValue) //根據屬性的key取得屬性的value,如果沒有key,則返回defaultValue
- public Object setProperty(String key, String value) //設置屬性
- public void list(PrintStream ouot) //屬性打印
- public void load(InputStream inStream) throws IOException //從輸入流中取出全部的屬性內容
- public void loadFormXML(InputStream in) throws IOException, InvalidPropertiesFormatException //從XML文件格式中讀取內容
- public void store(OutputStream os, String comment) throws IOException //將屬性內容通過輸出流輸出,同時聲明屬性的註釋
- public void storeToXML(OutputStream os, String comment) throws IOException //以XML文件格式輸出屬性,默認編碼
- public void storeToXML(OutputStream os, String comment, String encoding) throws IOException //以XML文件格式輸出,用戶指定默認編碼
import java.io.*;
import java.util.Properties;
/**
* Created by Javen on 2018/8/24.
*/
public class PropertiesDemo {
public static void main(String args[]) {
writePropertiesFile(); //寫 Properties 文件
readPropertiesFile(); //讀 Properties 文件
}
public static void writePropertiesFile() {
File file = new File("D:" + File.separator + "PropertiesDemoWrite.txt");
File file2 = new File("D:" + File.separator + "PropertiesDemoWriteXml.txt");
Properties properties = new Properties();
properties.setProperty("javen", "19950601");
properties.setProperty("nanshen", "19960101");
properties.setProperty("kunshen", "19940101");
properties.setProperty("zuqiang", "19940201");
try {
properties.store(new FileOutputStream(file), "PropertiesDemo");//寫文件
properties.storeToXML(new FileOutputStream(file2), "PropertiesDemoXml", "utf-8");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void readPropertiesFile() {
File file = new File("D:" + File.separator + "PropertiesDemoWrite.txt");
File file2 = new File("D:" + File.separator + "PropertiesDemoWriteXml.txt");
Properties properties = new Properties();
Properties properties2 = new Properties();
try {
properties.load(new FileInputStream(file));
properties2.loadFromXML(new FileInputStream(file2));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String jw = properties.getProperty("javen");
String ns = properties.getProperty("nanshen");
String zq = properties.getProperty("gangge");//不存在的key
String ks = properties.getProperty("kunshen");
System.out.println( jw + "\n" + ns + "\n" + zq + "\n" + ks);
}
}