Att*_*cus 8 java storage android
在我的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..
}
Run Code Online (Sandbox Code Playgroud)
在Android应用程序内部存储此类数据结构的最佳方法是什么?对不起,如果这看起来像一个愚蠢的问题,我对Android很新.提前致谢.
Ste*_* P. 16
HashMap是可序列化的,因此您可以将FileInputStream和FileOutputStream与ObjectInputStream和ObjectOutputStream结合使用.
要将您HashMap的文件写入:
FileOutputStream fileOutputStream = new FileOutputStream("myMap.whateverExtension");
ObjectOutputStream objectOutputStream= new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(myHashMap);
objectOutputStream.close();
Run Code Online (Sandbox Code Playgroud)
要从HashMap文件中读取:
FileInputStream fileInputStream = new FileInputStream("myMap.whateverExtension");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Map myNewlyReadInMap = (HashMap) objectInputStream.readObject();
objectInputStream.close();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8679 次 |
| 最近记录: |