簡體   English   中英

如何將HashMap寫入txt文件?

[英]How to write a HashMap to a txt file?

我有一個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;
}
 }

非常感謝您的幫助。

謝謝

更改DataPoint以實現java.io.Serializable並使用ObjectOutputStream.writeObject / ObjectInputStream.readObject。 所有Java SE集合實現都是可序列化的

使您的數據點類可序列化,並在使用以下代碼從文本文件中讀取和寫入地圖之后:File f = new File(“ myfile.txt”); HashMap> hashMap = new HashMap>();

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());`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM