How can I store a data structure such as a Hashmap internally in Android?

六眼飞鱼酱① 提交于 2019-12-03 13:00:39

HashMap is serializable, so you could just use a FileInputStream and FileOutputStream in conjunction with ObjectInputStream and ObjectOutputStream.

To write your HashMap to a file:

FileOutputStream fileOutputStream = new FileOutputStream("myMap.whateverExtension");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream);

objectOutputStream.writeObject(myHashMap);
objectOutputStream.close();

To read the HashMap from a file:

FileInputStream fileInputStream  = new FileInputStream("myMap.whateverExtension");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

Map myNewlyReadInMap = (HashMap) objectInputStream.readObject();
objectInputStream.close();

+1 for Steve P's answer but it does not work directly and while reading I get a FileNotFoundException, I tried this and it works well.

To Write,

try 
{
  FileOutputStream fos = context.openFileOutput("YourInfomration.ser", Context.MODE_PRIVATE);
  ObjectOutputStream oos = new ObjectOutputStream(fos);
  oos.writeObject(myHashMap);
  oos.close();
} catch (IOException e) {
  e.printStackTrace();
}

And to Read

try 
{
  FileInputStream fileInputStream = new FileInputStream(context.getFilesDir()+"/FenceInformation.ser");
  ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
  Map myHashMap = (Map)objectInputStream.readObject();
}
catch(ClassNotFoundException | IOException | ClassCastException e) {
  e.printStackTrace();
}

Writing:

FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream s = new ObjectOutputStream(fos);
s.writeObject(eventStorage);
s.close();

Reading is done in the inverse way and casting to your type in readObject

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!