aboutsummaryrefslogtreecommitdiff
path: root/src/main/persistence/FS.java
diff options
context:
space:
mode:
Diffstat (limited to 'src/main/persistence/FS.java')
-rw-r--r--src/main/persistence/FS.java46
1 files changed, 46 insertions, 0 deletions
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: <pre>O_WRONLY | O_TRUNC | O_CREAT</pre>
+ * 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();
+ }
+}