|
1 | 1 | package com.iluwatar; |
2 | 2 |
|
| 3 | +import java.io.FileInputStream; |
| 4 | +import java.io.FileNotFoundException; |
3 | 5 | import java.io.FileOutputStream; |
4 | 6 | import java.io.IOException; |
| 7 | +import java.io.ObjectInputStream; |
5 | 8 | import java.io.ObjectOutputStream; |
6 | 9 | import java.util.HashMap; |
7 | 10 | import java.util.Map; |
8 | 11 |
|
9 | 12 | public class RainbowFishSerializer { |
10 | 13 |
|
11 | | - public void write(RainbowFish rainbowFish, String filename) { |
| 14 | + public static void write(RainbowFish rainbowFish, String filename) throws IOException { |
12 | 15 | Map<String, String> map = new HashMap<>(); |
13 | 16 | map.put("name", rainbowFish.getName()); |
14 | 17 | map.put("age", String.format("%d", rainbowFish.getAge())); |
15 | 18 | map.put("lengthMeters", String.format("%d", rainbowFish.getLengthMeters())); |
16 | 19 | map.put("weightTons", String.format("%d", rainbowFish.getWeightTons())); |
17 | | - try { |
18 | | - FileOutputStream fileOut = new FileOutputStream("fish.ser"); |
19 | | - ObjectOutputStream objOut = new ObjectOutputStream(fileOut); |
20 | | - objOut.writeObject(map); |
21 | | - objOut.close(); |
22 | | - fileOut.close(); |
23 | | - } catch (IOException e) { |
24 | | - e.printStackTrace(); |
25 | | - } |
| 20 | + FileOutputStream fileOut = new FileOutputStream(filename); |
| 21 | + ObjectOutputStream objOut = new ObjectOutputStream(fileOut); |
| 22 | + objOut.writeObject(map); |
| 23 | + objOut.close(); |
| 24 | + fileOut.close(); |
26 | 25 | } |
27 | 26 |
|
28 | | -// public RainbowFish read(String filename) { |
29 | | -// } |
| 27 | + public static RainbowFish read(String filename) throws IOException, ClassNotFoundException { |
| 28 | + Map<String, String> map = null; |
| 29 | + FileInputStream fileIn = new FileInputStream(filename); |
| 30 | + ObjectInputStream objIn = new ObjectInputStream(fileIn); |
| 31 | + map = (Map<String, String>) objIn.readObject(); |
| 32 | + objIn.close(); |
| 33 | + fileIn.close(); |
| 34 | + return new RainbowFish(map.get("name"), |
| 35 | + Integer.parseInt(map.get("age")), |
| 36 | + Integer.parseInt(map.get("lengthMeters")), |
| 37 | + Integer.parseInt(map.get("weightTons"))); |
| 38 | + } |
30 | 39 | } |
0 commit comments