在修改properties文件内容时。遇到一个坑,那就是在保存修改文件内容的时候需要用到一个输出流,如果这个属性文件不是放在assets文件夹下是特别容易获取到该文件以及其输出流,如果是放在assets文件夹下就总是出找不到文件的异常。
最后差了半天终于找到了一个获取assets下文件的输出流的方法:
FileOutputStream fos = context.openFileOutput("a.properties",Context.MODE_PRIVATE);
以下是完整的代码片段
public static boolean putEntry(final Context context,final String key , final String value){
InputStreamReader in = null;
Properties props = new Properties();
try {
in = new InputStreamReader(context.getAssets().open("a.properties"), "UTF-8");
props.load(in);
props.put(key, value);
FileOutputStream fos = context.openFileOutput("a.properties",Context.MODE_PRIVATE);
props.store(fos, "update key:"+key);
//不要忘记flush。这个输出流不用调close方法,是自关闭的。
fos.flush();
return true;
} catch (IOException e) {
e.printStackTrace();
return false;
}
}