Java 操作 properties 文件
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;public class SetSystemProperty {
//屬性文件的路徑
static String profilepath="mail.properties";
/*** 采用靜態方法 */ private static Properties props = new Properties(); static { try { props.load(new FileInputStream(profilepath)); } catch (FileNotFoundException e) { e.printStackTrace(); System.exit(-1); } catch (IOException e) { System.exit(-1); } } /** * 讀取屬性文件中相應鍵的值 * @param key * 主鍵 * @return String */ public static String getKeyValue(String key) { return props.getProperty(key); } /** * 根據主鍵key讀取主鍵的值value * @param filePath 屬性文件路徑 * @param key 鍵名 */ public static String readValue(String filePath, String key) { Properties props = new Properties(); try { InputStream in = new BufferedInputStream(new FileInputStream( filePath)); props.load(in); String value = props.getProperty(key); System.out.println(key +"鍵的值是:"+ value); return value; } catch (Exception e) { e.printStackTrace(); return null; } } /** * 更新(或插入)一對properties信息(主鍵及其鍵值) * 如果該主鍵已經存在,更新該主鍵的值; * 如果該主鍵不存在,則插件一對鍵值。 * @param keyname 鍵名 * @param keyvalue 鍵值 */ public static void writeProperties(String keyname,String keyvalue) { try { // 調用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。 // 強制要求為屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。 OutputStream fos = new FileOutputStream(profilepath); props.setProperty(keyname, keyvalue); // 以適合使用 load 方法加載到 Properties 表中的格式, // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流 props.store(fos, "Update '" + keyname + "' value"); } catch (IOException e) { System.err.println("屬性文件更新錯誤"); } } /** * 更新properties文件的鍵值對 * 如果該主鍵已經存在,更新該主鍵的值; * 如果該主鍵不存在,則插件一對鍵值。 * @param keyname 鍵名 * @param keyvalue 鍵值 */ public static void updateProperties(String keyname,String keyvalue) { try { props.load(new FileInputStream(profilepath)); // 調用 Hashtable 的方法 put,使用 getProperty 方法提供并行性。 // 強制要求為屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。 OutputStream fos = new FileOutputStream(profilepath); props.setProperty(keyname, keyvalue); // 以適合使用 load 方法加載到 Properties 表中的格式, // 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流 props.store(fos, "Update '" + keyname + "' value"); } catch (IOException e) { System.err.println("屬性文件更新錯誤"); } } //測試代碼 public static void main(String[] args) { readValue("mail.properties", "jdbc_mysql"); writeProperties("jdbc_mysql", "127.0.0.1"); writeProperties("username", "root"); writeProperties("password", "123"); updateProperties("password", "456"); System.out.println("操作完成"); }
} </pre>
本文由用戶 cm54 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!