如何在安卓系统内部存储Hashmap等数据结构



在我的Android应用程序中,我试图使用内部存储来存储Map结构,例如:Map<String, Map<String, String>>。我已经研究过使用SharedPreferences,但正如您所知,这只适用于存储原始数据类型。我尝试使用FileOutputStream,但它只允许我以字节为单位写入。。。我是否需要以某种方式序列化Hashmap,然后写入文件?

我试着通读一遍http://developer.android.com/guide/topics/data/data-storage.html#filesInternal但我似乎找不到解决办法。

下面是我尝试做的一个例子:

private void storeEventParametersInternal(Context context, String eventId, Map<String, String> eventDetails){
Map<String,Map<String,String>> eventStorage = new HashMap<String,Map<String,String>>();
Map<String, String> eventData = new HashMap<String, String>();
String REQUEST_ID_KEY = randomString(16);
.   //eventData.put...
.   //eventData.put...
eventStorage.put(REQUEST_ID_KEY, eventData);
FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
fos.write(eventStorage) //This is wrong but I need to write to file for later access..
}

在Android应用程序中内部存储这种类型的数据结构的最佳方法是什么?很抱歉,如果这看起来像是一个愚蠢的问题,我是安卓系统的新手。提前谢谢。

HashMap是可序列化的,因此您可以将FileInputStream和FileOutputStream与ObjectInputStream和ObjectOutputStream结合使用。

HashMap写入文件:

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

从文件中读取HashMap

FileInputStream fileInputStream  = new FileInputStream("myMap.whateverExtension");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myNewlyReadInMap = (HashMap) objectInputStream.readObject();
objectInputStream.close();
Steve p的答案为

+1,但它不能直接起作用,在阅读时我得到了一个FileNotFoundException,我尝试了一下,效果很好。

写入,

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();
}

并读取

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();
}

写入:

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

读取以相反的方式完成,并在readObject 中转换为您的类型

最新更新