原创文章,如有转载,请注明出处:http://blog.csdn.net/myth13141314/article/details/61413096
开发过程中经常遇到的一个需求就是设置功能,实现的思路一般是动态地本地保存更新设置。保存的方法一般就是如下三种:
SharePreference保存数据库保存Properties保存到文件
今天介绍的就是Properties的方式
首先将初始化的配置保存在项目中的raw文件夹下,如图:
Properties的文件格式如下:
//字段名=值
language=English(United States)
region=US
资源文件准备好以后,就看Properties的用法了
从文件加载Properties和保存Properties到本地文件
public static Properties
getProperties() {
Properties properties =
new Properties();
try {
FileInputStream inputStream =
new FileInputStream(getFile());
properties.load(inputStream);
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
return properties;
}
public static void saveProperties(Properties properties) {
try {
OutputStream outputStream =
new FileOutputStream(getFile());
properties.store(outputStream,
"");
outputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
读取项目中raw文件夹下的Properties文件
public static Properties
getPropertiesFromRaw(Context context) {
Properties properties =
new Properties();
try {
InputStream inputStream = context.getResources().openRawResource(R.raw.setting);
properties.load(inputStream);
inputStream.close();
}
catch (Exception e) {
e.printStackTrace();
}
return properties;
}
更新Properties的值
//用上面写好的getProperties()方法获取
Properties对象
Properties properties = getProperties();
//更新
Properties的值,(
String keyName,
String keyValue)
properties.setProperty(keyName, keyValue);
//保存
Properties到本地,用上面写好的saveProperties(Perperties properties)方法
saveProperties(properties);
通过以上的步骤,我们就实现了用Properties的方法来保存一些用户的设置到本地,基本实现了设置功能。
需要注意的是,以上保存的设置文件是保存在SD卡里的,用户可能会删除配置文件,所以在读取文件时需要考虑文件不存在的情况,可以恢复初始化设置,也可以结合其他的保存方式。
转载请注明原文地址: https://ju.6miu.com/read-26081.html