From 578b7d1db256d9a582cef45ae5d13d858a977416 Mon Sep 17 00:00:00 2001 From: Yuuta Liang Date: Thu, 26 Oct 2023 05:00:12 +0800 Subject: Add persistence Signed-off-by: Yuuta Liang --- src/main/persistence/FS.java | 46 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 src/main/persistence/FS.java (limited to 'src/main/persistence/FS.java') diff --git a/src/main/persistence/FS.java b/src/main/persistence/FS.java new file mode 100644 index 0000000..3b5222d --- /dev/null +++ b/src/main/persistence/FS.java @@ -0,0 +1,46 @@ +package persistence; + +import model.asn1.exceptions.InvalidDBException; +import org.json.JSONException; +import org.json.JSONObject; +import org.json.JSONTokener; + +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.StandardOpenOption; + +/** + * Util class for file-system IO. + */ +public class FS { + /** + * EFFECTS: Read and decode the content of given path as UTF-8 into JSON. + * Throws {@link InvalidDBException} if IO error occurs or the input cannot be parsed. + */ + public static JSONObject read(Path path) throws InvalidDBException { + try { + final InputStream fd = Files.newInputStream(path, StandardOpenOption.READ); + final JSONObject obj = new JSONObject(new JSONTokener(fd)); + fd.close(); + return obj; + } catch (IOException | JSONException e) { + throw new InvalidDBException("Cannot read or parse the file", e); + } + } + + /** + * EFFECTS: Write the UTF-8 encoded JSON to the given path. + * open(2) parameters:
O_WRONLY | O_TRUNC | O_CREAT
+ * Throws {@link IOException} if the file cannot be opened or written. + */ + public static void write(Path path, JSONObject obj) throws IOException { + final OutputStream fd = Files.newOutputStream(path, + StandardOpenOption.WRITE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.CREATE); + fd.write(obj.toString().getBytes(StandardCharsets.UTF_8)); + fd.close(); + } +} -- cgit v1.2.3