|
| 1 | +package com.javabooks; |
| 2 | + |
| 3 | +import java.io.*; |
| 4 | +import java.util.*; |
| 5 | + |
| 6 | +public class JsonStorage implements BookStorage { |
| 7 | + |
| 8 | + @Override |
| 9 | + public void save(List<Book> books) throws IOException { |
| 10 | + BufferedWriter w = new BufferedWriter(new FileWriter("books.json")); |
| 11 | + w.write("[\n"); |
| 12 | + for (int i = 0; i < books.size(); i++){ |
| 13 | + Book b = books.get(i); |
| 14 | + w.write(" {\n"); |
| 15 | + w.write(" \"title\": \"" + b.getTitle() + "\",\n"); |
| 16 | + w.write(" \"author\": \"" + b.getAuthor() + "\",\n"); |
| 17 | + w.write(" \"year\": " + b.getYear() + ",\n"); |
| 18 | + w.write(" \"isbn\": \"" + b.getIsbn() + "\",\n"); |
| 19 | + w.write(" \"borrowed\": " + b.isBorrowed() + "\n"); |
| 20 | + w.write(" }" + (i < books.size() - 1 ? "," : "") + "\n"); |
| 21 | + } |
| 22 | + w.write("]"); |
| 23 | + w.close(); |
| 24 | + } |
| 25 | + |
| 26 | + @Override |
| 27 | + public List<Book> load() throws IOException { |
| 28 | + List<Book> list = new ArrayList<>(); |
| 29 | + File f = new File("books.json"); |
| 30 | + if (!f.exists()) return list; |
| 31 | + |
| 32 | + BufferedReader r = new BufferedReader(new FileReader(f)); |
| 33 | + String json = r.lines().reduce("", (a, b) -> a + b); |
| 34 | + r.close(); |
| 35 | + |
| 36 | + json = json.replace("[", "").replace("]", ""); |
| 37 | + String[] entries = json.split("\\},\\{"); |
| 38 | + |
| 39 | + for (String e : entries){ |
| 40 | + String clean = e.replace("{", "").replace("}", ""); |
| 41 | + String[] parts = clean.split(","); |
| 42 | + |
| 43 | + Map<String, String> map = new HashMap<>(); |
| 44 | + |
| 45 | + for (String p : parts){ |
| 46 | + String[] kv = p.split(":", 2); |
| 47 | + map.put( |
| 48 | + kv[0].replace("\"", "").trim(), |
| 49 | + kv[1].replace("\"", "").trim() |
| 50 | + ); |
| 51 | + } |
| 52 | + |
| 53 | + Book b = new Book( |
| 54 | + map.get("title"), |
| 55 | + map.get("author"), |
| 56 | + Integer.parseInt(map.get("year")), |
| 57 | + map.get("isbn") |
| 58 | + ); |
| 59 | + |
| 60 | + if (Boolean.parseBoolean(map.get("borrowed"))) b.borrow(); |
| 61 | + |
| 62 | + list.add(b); |
| 63 | + } |
| 64 | + return list; |
| 65 | + } |
| 66 | +} |
0 commit comments