Java讀寫配置檔案properties
阿新 • • 發佈:2019-02-05
1.新建一個test.properties檔案,裡面的值是pageNo=1
2.下面的程式碼是從百度中找到然後修改過的,因為直接填寫filepath根本不行,在讀的時候用Thread.currentThread().getClass().getResourceAsStream("/test.properties");,在寫的時候用Thread.currentThread().getClass().getResource("/test.properties").getPath(),這樣來表示路徑;
3.後來發現properties檔案一般只是用來做常量的讀入,而變數的寫入開啟檔案後根本不會變化,後來又改用txt檔案來實現讀寫。
String filepath=System.getProperty("user.dir"); //得到當前路徑
/**
* 根據主鍵key讀取主鍵的值value* @param filePath 屬性檔案路徑
* @param key 鍵名
*/
public static String readValue() {
Properties props = new Properties();
try {
//InputStream in = new BufferedInputStream(new FileInputStream(profilepath));InputStream in = Thread.currentThread().getClass().getResourceAsStream("/test.properties");
props.load(in);
String value = props.getProperty("pageNo");
System.out.println("pageNo鍵的值是:"+ value);
in.close();
return value;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 更新(或插入)一對properties資訊(主鍵及其鍵值)
* 如果該主鍵已經存在,更新該主鍵的值;
* 如果該主鍵不存在,則外掛一對鍵值。
* @param keyname 鍵名
* @param keyvalue 鍵值
*/
public static void writeProperties(String keyname,int keyvalue) {
Properties props = new Properties();
System.out.println(keyvalue);
try {
// 呼叫 Hashtable 的方法 put,使用 getProperty 方法提供並行性。
// 強制要求為屬性的鍵和值使用字串。返回值是 Hashtable 呼叫 put 的結果。
OutputStream fos = new FileOutputStream(Thread.currentThread().getClass().getResource("/test.properties").getPath());
props.setProperty(keyname, keyvalue+"");
// 以適合使用 load 方法載入到 Properties 表中的格式,
// 將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
props.store(fos, "Update '" + keyname + "' value");
fos.close();
} catch (IOException e) {
System.err.println("屬性檔案更新錯誤");
}
}