先看下Properties类的继承结构
Properties 类表示了一个持久的属性集。Properties 可保存在流中或从流中加载。属性列表中每个键及其对应值都是一个字符串。
一个属性列表可包含另一个属性列表作为它的“默认值”;如果未能在原有的属性列表中搜索到属性键,则搜索第二个属性列表。
因为 Properties 继承于 Hashtable,所以可对 Properties 对象应用 put 和 putAll 方法。但不建议使用这两个方法,因为它们允许调用者插入其键或值不是 String 的项。相反,应该使用 setProperty 方法。如果在“不安全”的 Properties 对象(即包含非 String 的键或值)上调用 store 或 save 方法,则该调用将失败。类似地,如果在“不安全”的 Properties 对象(即包含非 String 的键)上调用 propertyNames 或 list 方法,则该调用将失败
- 使用Properties保存数据
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Properties properties = new Properties();
try {
FileOutputStream fos = new FileOutputStream(new File(getCacheDir(), "config"));
properties.setProperty("name", "wuxiaoqi");
properties.setProperty("age", "24");
properties.store(fos, null);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
运行程序后,使用ADM可以看到文件config
导出文件查看文件内容可以看到已经成功保存的数据
#Sat Jul 08 07:09:37 GMT+00:00 2017
name=wuxiaoqi
age=24
- 使用Properties从流中查看数据
properties = new Properties();
try {
FileInputStream fis = new FileInputStream(new File(getCacheDir(), "config"));
properties.load(fis);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
Toast.makeText(this, "name:" + properties.get("name") + "\n" + "age:" + properties.get("age"), Toast.LENGTH_SHORT).show();
运行程序后会看到Toast显示name和age的值与我们之前保存的一致。
- 对使用Properties类的简单封装
public class AppConfig {
private static final String APP_CONFIG = "config";
private static AppConfig instance;
private Context mContext;
private AppConfig(Context context) {
mContext = context.getApplicationContext();
}
public static AppConfig getInstance(Context context) {
if (instance == null) {
synchronized (AppConfig.class) {
if (instance == null) {
instance = new AppConfig(context);
}
}
}
return instance;
}
private Properties get() {
FileInputStream fis = null;
Properties props = new Properties();
try {
fis = new FileInputStream(new File(mContext.getCacheDir(), APP_CONFIG));
props.load(fis);
fis.close();
} catch (Exception e) {
e.printStackTrace();
}
return props;
}
/**
* 对外提供的get方法
* @param key
* @return
*/
public String get(String key) {
Properties props = get();
return (props != null) ? props.getProperty(key) : null;
}
private void setProps(Properties p) {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(new File(mContext.getCacheDir(), APP_CONFIG));
p.store(fos, null);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 对外提供的保存key value方法
* @param key
* @param value
*/
public void set(String key, String value) {
Properties props = get();
props.setProperty(key, value);
setProps(props);
}
/**
* 对外提供的删除方法
* @param key
*/
public void remove(String... key) {
Properties props = get();
for (String k : key) {
props.remove(k);
}
setProps(props);
}
}
到这里Properties的使用就讲解完了,有兴趣的同学可以试试