用類java.util.Properties讀取、寫入*.properties文件
備註:該文中提到的方法針對*.txt類型的文件同樣適用
目錄結構如圖所示:
文件如下圖所示:
簡單代碼如下所示:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Properties;
public class propertiesTest {
public static void main(String[] args) {
try {
// 讀取*.properties文件
FileInputStream stream = new FileInputStream("conf/test.properties");
Properties properties = new Properties();
properties.load(stream);
// 1、讀取整個*.properties文件內容
properties.list(System.out);
// 2、按鍵值對的方式讀取
String name = properties.getProperty("username");
// 如果配置文件中有中文
name=new String(name.getBytes("ISO-8859-1"), "UTF-8");// 處理中文亂碼
System.out.println(name);//admin
// 3、循環遍歷讀取
for(Object obj:properties.keySet()){
String key = (String)obj;
String value = properties.getProperty(key);
System.out.println("key:"+key+",value:"+value);
}
// 寫入並保存*.properties文件
// 改變配置文件中的值
properties.setProperty("username","modifyUsername");
// 增加鍵值對
properties.put("age", "18");
// 創建新文件並保存
// 1、保存文件方法1-通過list方法將Properties內容寫入Properties文件
PrintStream print1 = new PrintStream(new File("conf/testNew1.properties"));//創建新文件
properties.list(print1);
// 2、保存文件方法2-通過store方法將Properties內容寫入Properties文件
PrintStream print2 = new PrintStream(new File("conf/testNew2.properties"));//創建新文件
properties.store(print2, "test");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}