Java的properties文件讀取和屬性修改

package Test;java

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Properties;字符串

public class AttributesrUtils{get

//根據屬性Key讀取屬性Value
public static String AttributesRead(String filePath, String key) {
Properties properties= new Properties();
try {
InputStream in = new BufferedInputStream (new FileInputStream(filePath));
properties.load(in);
String value = properties.getProperty(key);
System.out.println(key + " = " + value);
return value;it

}catch (IOException e) {
e.printStackTrace();
return null;
}
}io

//讀取Properties的所有信息
public static void GetAllProperties(String filePath) throws IOException {
Properties properties= new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = properties.propertyNames(); //獲得配置文件的名字table

while(en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = properties.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}class

}import

//寫入Properties信息
public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
Properties pps = new Properties();配置

InputStream in = new FileInputStream(filePath);
//從輸入流中讀取屬性列表(鍵和元素對)
pps.load(in);
//調用 Hashtable 的方法 put。使用 getProperty 方法提供並行性。
//強制要求爲屬性的鍵和值使用字符串。返回值是 Hashtable 調用 put 的結果。
OutputStream out = new FileOutputStream(filePath);
pps.setProperty(pKey, pValue);
//以適合使用 load 方法加載到 Properties 表中的格式,
//將此 Properties 表中的屬性列表(鍵和元素對)寫入輸出流
pps.store(out, "Update " + pKey + " name");
}date

public static void main(String [] args) throws IOException{
String value = GetValueByKey("data/config.properties", "name");
System.out.println(value);
GetAllProperties("data/config.properties");
WriteProperties("data/config.properties","long", "212");
}

}

相關文章
相關標籤/搜索