2015-04-28 23:59:30 +03:00
|
|
|
package com.iluwatar;
|
|
|
|
|
2015-04-29 18:50:08 +03:00
|
|
|
import java.io.FileInputStream;
|
|
|
|
import java.io.FileNotFoundException;
|
2015-04-28 23:59:30 +03:00
|
|
|
import java.io.FileOutputStream;
|
|
|
|
import java.io.IOException;
|
2015-04-29 18:50:08 +03:00
|
|
|
import java.io.ObjectInputStream;
|
2015-04-28 23:59:30 +03:00
|
|
|
import java.io.ObjectOutputStream;
|
|
|
|
import java.util.HashMap;
|
|
|
|
import java.util.Map;
|
|
|
|
|
|
|
|
public class RainbowFishSerializer {
|
|
|
|
|
2015-04-29 18:50:08 +03:00
|
|
|
public static void write(RainbowFish rainbowFish, String filename) throws IOException {
|
2015-04-28 23:59:30 +03:00
|
|
|
Map<String, String> map = new HashMap<>();
|
|
|
|
map.put("name", rainbowFish.getName());
|
|
|
|
map.put("age", String.format("%d", rainbowFish.getAge()));
|
|
|
|
map.put("lengthMeters", String.format("%d", rainbowFish.getLengthMeters()));
|
|
|
|
map.put("weightTons", String.format("%d", rainbowFish.getWeightTons()));
|
2015-04-29 18:50:08 +03:00
|
|
|
FileOutputStream fileOut = new FileOutputStream(filename);
|
|
|
|
ObjectOutputStream objOut = new ObjectOutputStream(fileOut);
|
|
|
|
objOut.writeObject(map);
|
|
|
|
objOut.close();
|
|
|
|
fileOut.close();
|
2015-04-28 23:59:30 +03:00
|
|
|
}
|
|
|
|
|
2015-04-29 18:50:08 +03:00
|
|
|
public static RainbowFish read(String filename) throws IOException, ClassNotFoundException {
|
|
|
|
Map<String, String> map = null;
|
|
|
|
FileInputStream fileIn = new FileInputStream(filename);
|
|
|
|
ObjectInputStream objIn = new ObjectInputStream(fileIn);
|
|
|
|
map = (Map<String, String>) objIn.readObject();
|
|
|
|
objIn.close();
|
|
|
|
fileIn.close();
|
|
|
|
return new RainbowFish(map.get("name"),
|
|
|
|
Integer.parseInt(map.get("age")),
|
|
|
|
Integer.parseInt(map.get("lengthMeters")),
|
|
|
|
Integer.parseInt(map.get("weightTons")));
|
|
|
|
}
|
2015-04-28 23:59:30 +03:00
|
|
|
}
|