Properties 類 (為了方便內(nèi)存中的數(shù)據(jù)持久化)
····最常用于java的配置文件
配置文件
(注意路徑,如果不是在src目錄下,請勿使用classload加載)

image.png

繼承hashTable (和Map的底層原理相同)
最常用于,存儲集合
以key=value 的 鍵值對的形式進行存儲值。 key值不能重復。
獲取jvm相關信息
/**獲取jvm的相關信息*/
private static void showJVMinfo() {
Properties ps = System.getProperties();
for (String s : ps.stringPropertyNames()) {
System.out.println(s+"="+ps.getProperty(s));
}
}
package ProPerties;
import java.io.*;
import java.util.Properties;
import java.util.Set;
/**
* Created by kumamon on 2021/5/27.
*
* 為了數(shù)據(jù)持久化
*
* android的SystemProperSties 就是這種
*
* 和 map 一樣,以 鍵 值 對的方式存儲數(shù)據(jù)
*
*/
public class PropertiesDemo {
public static void main(String[] args) throws IOException {
Properties properties=new Properties();
set(properties);
get(properties);
write(properties);
reader();
//showJVMinfo();
}
/**獲取jvm的相關信息*/
private static void showJVMinfo() {
Properties ps = System.getProperties();
for (String s : ps.stringPropertyNames()) {
System.out.println(s+"="+ps.getProperty(s));
}
}
/**
* 以鍵值對的方式存儲
* 和map相同
*
* @param ps*/
private static void set(Properties ps) {
ps.setProperty("迪麗熱巴","18");
ps.setProperty("古力娜扎","17");
ps.setProperty("馬爾扎哈","10");
ps.setProperty("趙麗穎","18");
}
/**
* 獲取Properties的數(shù)據(jù)*/
private static void get(Properties ps) {
String dlrb = (String) ps.getProperty("迪麗熱巴");
System.out.println(dlrb); //18
String unkown = (String) ps.getProperty("迪麗熱巴1","沒有數(shù)據(jù)");
System.out.println(unkown); //沒有數(shù)據(jù)
Set<String> strings = ps.stringPropertyNames();
/**
*
key=趙麗穎 值=18
key=古力娜扎 值=17
key=馬爾扎哈 值=10
key=迪麗熱巴 值=18
* */
for (String s : strings) {
System.out.println("key="+s+" 值="+ps.getProperty(s));
}
}
/**
* 持久化,將內(nèi)存中的數(shù)據(jù)存儲到 硬盤中
*
ps.store(fileWriter,""); 第二個參數(shù)為解釋說明,中文會亂碼 一般不寫
趙麗穎 18
古力娜扎 17
馬爾扎哈 10
迪麗熱巴 18
存儲到 Test.prop中
*
* @param ps*/
private static void write(Properties ps) throws IOException {
FileWriter fileWriter =new FileWriter("E:\\Java_demo\\demo01\\src\\ProPerties\\Test.prop");
ps.store(fileWriter,"");
//以xml格式存儲,只能使用字節(jié)流
ps.storeToXML(new FileOutputStream("E:\\Java_demo\\demo01\\src\\ProPerties\\Test.xml"), "");
}
/**
* 讀取Test.prop中的數(shù)據(jù)
* */
private static void reader() throws IOException {
FileReader fileReader=new FileReader("E:\\Java_demo\\demo01\\src\\ProPerties\\Test.prop");
Properties properties=new Properties();
properties.load(fileReader);
for (String s : properties.stringPropertyNames()) {
System.out.println("由Test.prop讀取"+s+"="+properties.getProperty(s));
}
}
}

image.png