更新存储在文件中的特定键的hashmap值

时间:2016-01-15 12:59:18

标签: java android file serialization hashmap

我使用下面的代码将HashMap写入文件。我想在file.Suppose中更新HashMap的特定值我想更新键"b"的值,保持其他值相同。我该怎么做?

  HashMap settinglist=new HashMap();
settinglist.put("a",”abc”);
settinglist.put("b",”def”);
settinglist.put("c",”hij”);
settinglist.put("d",”klm”);
settinglist.put("e", “nop”);
SettingsObjectSerializer.serializeObject(getApplicationContext(),settinglist);

SettingsObjectSerializer

 public class SettingsObjectSerializer {
        private final static String FILENAME = "retrytimeout";
        private static HashMap mSettingList = null;
        public static boolean serializeObject(Context ctx, HashMap retrytimeout) {
            boolean success = false;
            try
            {
                FileOutputStream fos = ctx.openFileOutput(FILENAME, Context.MODE_PRIVATE);
                ObjectOutputStream os = new ObjectOutputStream(fos);
                os.writeObject(retrytimeout);
                os.close();
                fos.close();
                if(retrytimeout == null) {
                    mSettingList = null;
                }
                success = true;
            }
            catch (IOException ex)
            {
                ex.printStackTrace();
                success = false;
            }
            return success;
        }
        public static HashMap getSerializedObject(Context ctx) {
            if (mSettingList != null) {
                return mSettingList;
            }
            try {
                FileInputStream fis =  ctx.openFileInput(FILENAME);
                ObjectInputStream is = new ObjectInputStream(fis);
                mSettingList = (HashMap) is.readObject();
                is.close();
                fis.close();
            } catch (IOException ex) {
                ex.printStackTrace();
            } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
            }
            return mSettingList;
        }
    }

1 个答案:

答案 0 :(得分:0)

将序列化对象读入HashMap,然后使用HashMap方法put(Object key, Object value);替换键的旧值" b"使用新值(因为只能有一个唯一键)。然后序列化HashMap并再次保存。 例如:

        //Your initialization
        HashMap settinglist=new HashMap();
        settinglist.put("a","abc");
        settinglist.put("b","def");
        settinglist.put("c","hij");
        settinglist.put("d","klm");
        settinglist.put("e", "nop");
        SettingsObjectSerializer.serializeObject(getApplicationContext(),settinglist);

        //Change the value linked to key "b" to "NEWVALUE"
        HashMap settings = SettingsObjectSerializer.getSerializedObject(getApplicationContext());
        settings.put("b", "NEWVALUE");
        SettingsObjectSerializer.serializeObject(getApplicationContext(),settings);