Android Propterties文件修改操作出現的問題

在修改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;
        }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章