java 和android Properties的应用,请看main方法
public class PropertiesUtils {
//根据Key读取Value
public static String GetValueByKey(String filePath, String key) {
Properties pps = new Properties();
try {
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
String value = pps.getProperty(key);
System.out.println(key + " = " + value);
return value;
}catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
}
//读取Properties的全部信息
public static void GetAllProperties(String filePath) throws IOException {
Properties pps = new Properties();
InputStream in = new BufferedInputStream(new FileInputStream(filePath));
pps.load(in);
Enumeration en = pps.propertyNames(); //得到配置文件的名字
while(en.hasMoreElements()) {
String strKey = (String) en.nextElement();
String strValue = pps.getProperty(strKey);
System.out.println(strKey + "=" + strValue);
}
}
//写入Properties信息
public static void WriteProperties (String filePath, String pKey, String pValue) throws IOException {
//props.load(context.openFileInput("config.properties"));// 安卓用的
//OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE);//安卓用的
Properties pps = new Properties();
InputStream in = new FileInputStream(filePath);
pps.load(in);
OutputStream out = new FileOutputStream(filePath);
//下面这段为安卓多出来的。主要是因为Context.Mode造成的。
Enumeration<?> e = pps.propertyNames();
if(e.hasMoreElements()){
while (e.hasMoreElements()) {
String s = (String) e.nextElement();
if (!s.equals(pKey)) {
pps.setProperty(s, pps.getProperty(s));
}
}
}
//上面这段为安卓多出来的。主要是因为Context.Mode造成的。
pps.setProperty(pKey, pValue);
pps.store(out, "Update " + pKey + " name");
}
public static void main(String [] args) throws IOException{
//WriteProperties("Test.properties","ttt", "333");
//GetValueByKey("Test.properties","Height");
GetAllProperties("Test.properties");
}
}
网友评论