2013-07-18 70 views
6

在我的Android应用程序中,我尝试使用内部存储来存储地图结构,如:Map<String, Map<String, String>>。我研究过使用SharedPreferences,但正如你所知,这只适用于存储原始数据类型。我试图使用FileOutputStream,但它只能让我以字节写...我需要以某种方式序列化Hashmap,然后写入文件?如何在Android内部存储数据结构(如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应用程序存储这种类型的数据结构的最佳方法?对不起,如果这看起来像一个愚蠢的问题,我是非常新的Android。提前致谢。

回答

14

HashMap是序列化的,所以你可以只结合使用FileInputStreamFileOutputStreamObjectInputStreamObjectOutputStream

要写HashMap到一个文件:

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

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

写作:

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

读书是在逆方式进行,并投射到您的类型的readObject

0

+1史蒂夫·普的答案,但它并不直接工作,而读我:

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

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

从文件中读取HashMap得到一个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(); 
}