Java 如何在Android内部存储Hashmap之类的数据结构?
在我的Android应用程序中,我试图使用内部存储存储一个映射结构,例如:Java 如何在Android内部存储Hashmap之类的数据结构?,java,android,storage,Java,Android,Storage,在我的Android应用程序中,我试图使用内部存储存储一个映射结构,例如:Map。我已经研究过如何使用SharedReferences,但是您知道,这只在存储基本数据类型时有效。我尝试使用FileOutputStream,但它只允许我以字节为单位进行写入…我是否需要以某种方式序列化Hashmap,然后写入文件 我试着通读一遍,但似乎找不到解决办法 下面是我正在尝试做的一个例子: private void storeEventParametersInternal(Context context,
Map
。我已经研究过如何使用SharedReferences
,但是您知道,这只在存储基本数据类型时有效。我尝试使用FileOutputStream
,但它只允许我以字节为单位进行写入…我是否需要以某种方式序列化Hashmap,然后写入文件
我试着通读一遍,但似乎找不到解决办法
下面是我正在尝试做的一个例子: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..
}
private void storeeventparameters内部(上下文上下文、字符串eventId、映射eventDetails){
Map eventStorage=new HashMap();
Map eventData=new HashMap();
字符串请求\u ID\u KEY=randomString(16);
.//eventData.put。。。
.//eventData.put。。。
eventStorage.put(请求\u ID\u键,eventData);
FileOutputStream fos=context.openFileOutput(事件\文件名,context.MODE \私有);
fos.write(eventStorage)//这是错误的,但我需要写入文件以供以后访问。。
}
在Android应用程序内部存储此类数据结构的最佳方法是什么?抱歉,如果这看起来像一个愚蠢的问题,我对Android非常陌生。提前感谢。写作:
FileOutputStream fos = context.openFileOutput(EVENT_FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream s = new ObjectOutputStream(fos);
s.writeObject(eventStorage);
s.close();
读取是以相反的方式完成的,并且在readObject中强制转换到您的类型是可序列化的,因此您可以将and与and结合使用 要将
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();
}