java.util.Properties

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");


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值