更新后无法从文件中读取HashMap

时间:2017-02-28 11:18:00

标签: android android-file

不确定这是否是罪魁祸首,但我不能再从文件中读取HashMap(昨天似乎工作)。以下是将HashMap保存到文件的代码:

try {
    File file = new File(getDir("data_directory", MODE_PRIVATE), "map_file");
    ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
    outputStream.writeObject(shopKeysAndNames);
    outputStream.flush();
    outputStream.close();

    Log.i(TAG, "written file length: " + file.length());

} catch (IOException e) {
    e.printStackTrace();
}

以下是从文件中读取HashMap的代码:

try {
    File file = new File(getDir("data_directory", MODE_PRIVATE), "map_file");

    Log.i(TAG, "file length: " + file.length());

    ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(file));
    HashMap <String, String> newMap = (HashMap <String, String> ) inputStream.readObject();

    inputStream.close();

    Log.i(TAG, "Contents of the array: " + newMap.toString());

} catch (IOException | ClassNotFoundException e) {
    e.printStackTrace();
}

读取HashMap始终为空。写入后和读取前的文件大小也相同。我做错了什么?

编辑 - 找到了罪魁祸首,写成空HashMap :( 谢谢你把注意力集中在它上面。这是为存储创建HashMap的代码,我不小心删除了将值放到HashMap中的行:

// Temporary hashmap to store keys and names of all goods
HashMap < String, String > shopKeysAndNames = new HashMap < > ();

// Put all goods to iterable
Iterable < DataSnapshot > iterable = dataSnapshot.getChildren();

// Iterate each good and store values to hashmap
for (DataSnapshot currentGood: iterable) {

 // Good key and name
 String goodKey = currentGood.getKey();
 String goodName = (String) currentGood.child("Name").getValue();

}

0 个答案:

没有答案