java.util.Properties 类可在所有java程序中应用;
在android 中,相对于xml解析更简单;
1.可以以文件形式保存和加载
<span style="font-size:18px;">import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Properties;
public Properties loadConfig(Context context, String file) {
Properties properties = new Properties();
try {
FileInputStream s = new FileInputStream(file);
properties.load(s);
} catch (Exception e) {
e.printStackTrace();
}
return properties;
}
public void saveConfig(Context context, String file, Properties properties) {
try {
FileOutputStream s = new FileOutputStream(file, false);
properties.store(s, "");
} catch (Exception e){
e.printStackTrace();
}
} </span>
<span style="font-size:18px;">Properties prop = new Properties();
prop.put("prop1", "abc");
prop.put("prop2", 1);
prop.put("prop3", 3.14);
saveConfig(this, "/sdcard/config.dat", prop); </span>
<span style="font-size:18px;">Properties prop = loadConfig(this, "/sdcard/config.dat");
String prop1 = prop.get("prop1"); </span>
2.直接从raw文件夹中的*.properties文件中读取(以id描述符打开raw资源文件)
<span style="font-size:18px;">private Properties loadProperties() {
// InputStream in = null;
// Properties props = null;
// try {
// in = getClass().getResourceAsStream(
// "/org/androidpn/client/client.properties");
// if (in != null) {
// props = new Properties();
// props.load(in);
// } else {
// Log.e(LOGTAG, "Could not find the properties file.");
// }
// } catch (IOException e) {
// Log.e(LOGTAG, "Could not find the properties file.", e);
// } finally {
// if (in != null)
// try {
// in.close();
// } catch (Throwable ignore) {
// }
// }
// return props;
Properties props = new Properties();
try {
int id = context.getResources().getIdentifier("androidpn", "raw",
context.getPackageName());
props.load(context.getResources().openRawResource(id));
} catch (Exception e) {
Log.e(LOGTAG, "Could not find the properties file.", e);
// e.printStackTrace();
}
return props;
}</span>
根据key取
props.getProperty("key", "default-value");