如何将HashMap写入txt文件?

时间:2014-02-02 08:26:41

标签: java android file-io hashmap

我有一个HashMap包含一些我要写入文件的数据,并重新加载文件的内容以形成相同的HashMap。

HashMap如下:

    HashMap<Long, List<DataPoint>> hashMap = new HashMap<Long, List<DataPoint>>();

DataPoint类如下:

public class DataPoint {

private int time;
private int songId;

public DataPoint(int songId, int time) {
    this.songId = songId;
    this.time = time;
}

public int getTime() {
    return time;
}

public int getSongId() {
    return songId;
}
 }

非常感谢帮助。

由于

2 个答案:

答案 0 :(得分:2)

更改DataPoint以实现java.io.Serializable并使用ObjectOutputStream.writeObject / ObjectInputStream.readObject。所有Java SE集合实现都是Serializable

答案 1 :(得分:2)

使您的数据点类可序列化,并在使用下面的代码从文本文件`File f = new File(“myfile.txt”)读取和写入您的地图;     的HashMap&GT; hashMap = new HashMap&gt;();

List<DataPoint> list = new ArrayList<DataPoint>();
list.add(new DataPoint(1, 1));
list.add(new DataPoint(2, 2));
hashMap.put(1L, list);

ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
oos.writeObject(hashMap);

oos.flush();
oos.close();

ObjectInputStream ois = new ObjectInputStream(new FileInputStream(f));
HashMap<Long, List<DataPoint>> returnedMap = (HashMap<Long, List<DataPoint>>) ois.readObject();
ois.close();
// Use returned object.
System.out.println(returnedMap.get(1L).size());`