在日常的Java程序開發中,Properties文件的讀寫是很常用的。經常有開發系統通過properties文件來當做配置文件,方便用戶對系統參數進行調整。
那么本片就來簡單的介紹下,如何使用Properties。
文件的讀取
Properties類提供了Load方法,支持以inputstream為參數,讀取配置文件。因此可以這樣:
Properties props = new Properties();
//如果配置文件放在類目錄下,可以直接通過類加載器讀取
props.load(new FileReader("D:\\test.properties"));
不過上面的讀取方法需要完整的文件路徑,顯然在開發中是很不方便的。
因此推薦下面這種方法,通過類加載器的路徑來讀取配置文件:
props.load(PropertiesTest.class.getClassLoader().getResourceAsStream(fileName));
屬性的讀寫
通過getProperty可以取到文件的屬性:
//獲取屬性值
System.out.println(props.getProperty("name"));
System.out.println(props.getProperty("age"));
System.out.println(props.getProperty("address","dalian"));//如果沒有拿到屬性值,會按照第二個參數作為默認值
//修改屬性值
props.setProperty("name", "ttt");
System.out.println(props.getProperty("name"));
配置持久化
如果需要在程序運行時,持久化配置文件,也可以使用store方法:
//持久化配置文件
File file = new File("D:\\result.properties");
Writer fw = new FileWriter(file);
props.store(fw, "conmments");
fw.close();
源碼測試
package xing.CodeJava.basic;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Writer;
import java.util.Properties;
public class PropertiesTest {
public static void main(String[] args) {
String fileName = "test.properties";
try {
//讀取配置文件
Properties props = new Properties();
// props.load(PropertiesTest.class.getClassLoader().getResourceAsStream(fileName));//如果配置文件放在類目錄下,可以直接通過類加載器讀取
props.load(new FileReader("D:\\TestCode\\CodeJava\\CodeJava\\src\\main\\java\\xing\\CodeJava\\basic\\test.properties"));
//獲取屬性值
System.out.println(props.getProperty("name"));
System.out.println(props.getProperty("age"));
System.out.println(props.getProperty("address","dalian"));//如果沒有拿到屬性值,會按照第二個參數作為默認值
//修改屬性值
props.setProperty("name", "ttt");
System.out.println(props.getProperty("name"));
//持久化配置文件
File file = new File("D:\\TestCode\\CodeJava\\CodeJava\\src\\main\\java\\xing\\CodeJava\\basic\\result.properties");
Writer fw = new FileWriter(file);
props.store(fw, "conmments");
fw.close();
}catch(Exception e){
e.printStackTrace();
}
}
}