将hashmap写入文件并从同一文件中读取时出错

时间:2018-06-11 09:42:06

标签: android android-studio-3.0 android-file

我需要创建一个文件并在每次收到id时为其添加一个id,我创建了一个文件并将代码添加到其中

  public static  void enterIdToFile(Context context, String questionId){

    HashMap<String, Integer> incrementedMap = new HashMap<>();
    incrementedMap.put(Id,1);
    QuestionLaunchCountModal questionLaunchCountModal = new QuestionLaunchCountModal();
    questionLaunchCountModal.setQuestionLaunchCount(incrementedMap);

    try {
        File outFile = new File(context.getExternalFilesDir("/"), Constants.answerdQuestionFile);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(outFile,true));
        oos.writeObject(incrementedMap);
        oos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }

}

此代码将我的id写入文件,我试图附加每个id。

现在从我使用的文件中读取

  if (Utils.isFilePresent(context, Constants.answerdQuestionFile)) {

        try {
            File file = new File(context.getExternalFilesDir("/"), Constants.answerdQuestionFile);
            FileInputStream is = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(is);
            questionLaunchCountModal1 = (QuestionLaunchCountModal) ois.readObject();
            ois.close();
            is.close();
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }

        if (null != questionLaunchCountModal1) {
            HashMap<String, Integer> incrementedMap = new HashMap<>();
            incrementedMap.putAll(questionLaunchCountModal1.getQuestionLaunchCount());
        }
    }
    return questionLaunchCountModal1;

但每次我尝试读取值时我只得到第一个条目..即使我在文件中有5个id,我只能读一个

0 个答案:

没有答案