X-Git-Url: https://mograsim.net/gitweb/?a=blobdiff_plain;f=net.mograsim.logic.ui%2Fsrc%2Fnet%2Fmograsim%2Flogic%2Fui%2Futil%2FJsonHandler.java;h=df48266622a22efe78cc8c18a907b0d2dcf2574c;hb=78c6c20a637ade903ee41b9e557bde0c30c08218;hp=94231a3d80ab65f48b716a1a1f21d131334c51d2;hpb=6432c12630fa3f80ec19bf23229844abd42105e3;p=Mograsim.git diff --git a/net.mograsim.logic.ui/src/net/mograsim/logic/ui/util/JsonHandler.java b/net.mograsim.logic.ui/src/net/mograsim/logic/ui/util/JsonHandler.java index 94231a3d..df482666 100644 --- a/net.mograsim.logic.ui/src/net/mograsim/logic/ui/util/JsonHandler.java +++ b/net.mograsim.logic.ui/src/net/mograsim/logic/ui/util/JsonHandler.java @@ -1,9 +1,12 @@ package net.mograsim.logic.ui.util; import java.io.BufferedReader; -import java.io.FileReader; +import java.io.FileInputStream; import java.io.FileWriter; import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.util.stream.Collectors; import com.google.gson.Gson; import com.google.gson.GsonBuilder; @@ -12,24 +15,42 @@ public class JsonHandler { private static Gson parser = new GsonBuilder().setPrettyPrinting().create(); - @SuppressWarnings("resource") public static T readJson(String path, Class type) throws IOException { - FileReader reader = new FileReader(path); - BufferedReader bf = new BufferedReader(reader); - bf.readLine(); // Skip version - String json = bf.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').reduce("", (x, y) -> x.concat(y)); - T params = parser.fromJson(json, type); - reader.close(); - return params; + try (FileInputStream jsonStream = new FileInputStream(path)) + { + return readJson(jsonStream, type); + } + } + + /** + * @param input The Stream is closed after being read + */ + public static T readJson(InputStream input, Class type) throws IOException + { + try (InputStreamReader reader = new InputStreamReader(input); BufferedReader bf = new BufferedReader(reader)) + { + return fromJson(bf.lines().collect(Collectors.joining("\n")), type); + } + } + + public static T fromJson(String src, Class type) + { + // TODO actually parse and compare version + String rawJson = src.lines().dropWhile(s -> s.length() == 0 || s.charAt(0) != '{').collect(Collectors.joining()); + return parser.fromJson(rawJson, type); } public static void writeJson(Object o, String path) throws IOException { - @SuppressWarnings("resource") - FileWriter writer = new FileWriter(path); - writer.write(String.format("mograsim version: %s\n", Version.current.toString())); - writer.write(parser.toJson(o)); - writer.close(); // TODO: Insure that writer is closed + try (FileWriter writer = new FileWriter(path)) + { + writer.write(toJson(o)); + } + } + + public static String toJson(Object o) + { + return String.format("mograsim version: %s\n%s", Version.jsonCompVersion.toString(), parser.toJson(o)); } }