Android 对 properties文件的读写操作

http://zouhuajian01.blog.163.com/blog/static/11769877201251410467309/

 

-、 放在res中的properties文件的读取,例如对放在assets目录中的setting.properties的读取:
PS:之所以这里只是有读取操作,而没有写的操作,是因为我发现不能对res下的资源文件进行操作,当然包括assets下的properties文件了。如对res资源目录下的properties进行写的操作,那么在你获得properties的FileOutputStream的实例时会报FileNotFoundException的异常。
代码如下(操作写成一个PropertiesUtil工具类):
setting.properties中的代码:

url=http://localhost:8080


PropertiesUtil 工具类:

public class PropertiesUtil {
private static Properties urlProps ;
public static Properties getProperties ( Context c ){
Properties props = new Properties ();
try { //方法一:通过activity中的context攻取 setting.properties的FileInputStream
InputStream in = c. getAssets().open(" setting.properties "); //方法二:通过class获取setting.properties的FileInputStream //InputStream in = PropertiesUtill.class. getResourceAsStream("/assets/ setting.properties "));
props.load(in);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlProps = props; //测试是否能获得setting.properties中url的值 System . out . println ( urlProps . getProperty ( "url" )); return urlProps ;
}
}


二、对不是放在res资源目录下的properties文件的操作,如放在activity 的 包(package)目录下的setting.properties文件的读写操作。
setting.properties的代码还是一样的,只是路径不同,而是在activity的包(如:com.jansun.activity)目录下:

url=http://localhost:8080

PropertiesUtil工具类:

public class PropertiesUtil {
private static Properties urlProps ;
private static final path = "/data/data/com.jansun.activity/setting.properties" ;
//private FileUtils fu = new FileUtils();
public static Properties getProperties(){
Properties props = new Properties();
try {
InputStream in = new FileInputStream(getSettingFile());
props.load(in);
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
urlProps = props;
return urlProps;
}
public static void setProperties( String param, String value ){
Properties props = new Properties();
try {
props.load(new FileInputStream( getSettingFile() ));
OutputStream out = new FileOutputStream(FileUtils.setting);
Enumeration<?> e = props.propertyNames();
if(e.hasMoreElements()){
while(e.hasMoreElements()){
String s = (String)e.nextElement();
if(!s.equals(param))
props.setProperty(s, props.getProperty(s));
}
}
props.setProperty(param, value);
props.store(out, null); //测试是否能够打印出最新的,刚刚修改的url的值
//System.out.println("setProperty success: " + props.getProperty(param));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static File getSettingFile(){ File setting = new File ( path ); if (! setting . exists ()) setting . createNewFile (); return setting ; }
}

 

http://bbs.csdn.net/topics/350188120

http://blog.csdn.net/howlaa/article/details/18305289

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值