Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

配置文件 Java 讀寫

Java 中常使用 .properties 檔案保存設定,例如資料庫連線資訊。Properties 類別繼承 Hashtable,以鍵值對方式儲存資料,適合讀取與寫入簡單設定。

讀取設定

Properties p = new Properties();
Reader reader = new FileReader("config.properties");
p.load(reader);
String driver = p.getProperty("Driver");
reader.close();

寫入設定

Properties p = new Properties();
Writer writer = new FileWriter("config.properties");
p.setProperty("url", "jdbc:mysql://localhost:3306/");
p.setProperty("user", "root");
p.store(writer, "this is comments");
writer.close();

config.properties 的內容通常不含空格與雙引號,例如:

Driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/
user=root
password=12345

將可變設定放入配置檔,可避免修改程式碼。例如 JDBC 工具類可從配置檔讀取 Driver、url、user 與 password,讓部署與維護更靈活。

Copyright © Linux教程網 All Rights Reserved