Ahsan Zaheer
Ahsan Zaheer

Reputation: 676

How to write a HashMap to a txt file?

I have a HashMap containing some data that I want to write to a file and reload the contents of the file to form the same HashMap.

HashMap is as follows:

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

And DataPoint class is as follows:

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;
}
 }

Help is much appreciated.

Thanks

Upvotes: 0

Views: 3831

Answers (2)

Naveen Ramawat
Naveen Ramawat

Reputation: 1445

Make your data point class as serializable and after use the below code to read and write your map from a text file ` 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());`

Upvotes: 2

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 135992

Change DataPoint to implement java.io.Serializable and use ObjectOutputStream.writeObject / ObjectInputStream.readObject. All Java SE collection implementations are Serializable

Upvotes: 2

Related Questions