Java 使用HashMap读写对象的arrayList
我想将“HashMap”写入并读取到文件中 我的“HashMap”是:Java 使用HashMap读写对象的arrayList,java,android,arraylist,hashmap,read-write,Java,Android,Arraylist,Hashmap,Read Write,我想将“HashMap”写入并读取到文件中 我的“HashMap”是: Map<String, ArrayList<Descipline>> mapDis = new HashMap<String, ArrayList<Descipline>>(); Map-mapDis=new HashMap(); 我这样写文件: String root = Environment.getExternalStorageDirectory().toString
Map<String, ArrayList<Descipline>> mapDis = new HashMap<String, ArrayList<Descipline>>();
Map-mapDis=new HashMap();
我这样写文件:
String root = Environment.getExternalStorageDirectory().toString();
Properties properties = new Properties();
for (Map.Entry<String, ArrayList<Descipline>> entry : mapDis.entrySet()){
properties.put(entry.getKey(), entry.getValue());
}
properties.store(new FileOutputStream(root + "/myMap.txt"), null);
String root=Environment.getExternalStorageDirectory().toString();
属性=新属性();
对于(Map.Entry:mapDis.entrySet()){
properties.put(entry.getKey(),entry.getValue());
}
store(新的FileOutputStream(root+“/myMap.txt”),null;
但我不知道怎么读
Map<String, ArrayList<Descipline>> load = new HashMap<String, ArrayList<Descipline>>();
Properties properties1 = new Properties();
properties1.load(new FileInputStream(root + "/myMap.txt"));
for (String key : properties1.stringPropertyNames()){
//something will be here to read file
}
Map load=newhashmap();
Properties properties1=新属性();
加载(新文件输入流(root+“/myMap.txt”);
for(字符串键:properties1.stringPropertyNames()){
//这里将有东西读取文件
}
您已经加载了该文件。在循环中,您正在读取文件(即映射)条目,因此只需再次使用put方法,它非常简单:java.util.Properties
是java.util.HashTable
的子类,它实现了java.util.map
,就像java.util.HashMap
一样。因此,您可以像保存时一样使用entrySet
进行迭代,同时提供键和值
但是请注意,
Properties
保存和加载要求键和值都是String
(一个.Properties文件是一个简化的'ini'文件),因此您可能需要查看java.io.Serializable
。如何读取该文件?我是这样读的,但它不起作用:“for(String键:properties1.stringPropertyNames()){load.put(key,properties1.get(key.toString());}”我是这样读文件的,我有一个java.util.ArrayList不能转换为java.lang.String:for(Map.Entry条目:load.entrySet()){load.put(entry.getKey(),entry.getValue());}或多或少。正如我所说,Properties
希望键和值是String
。您的值是ArrayList
,它不是String
。请理解HashMap
和Properties
都是Map
,因此以这种方式在它们之间复制值是毫无意义的。您能发布De>吗scipline
class?然后我可以给你一个使用Serializable
的例子。