aboutsummaryrefslogtreecommitdiff
path: root/src/main/persistence/FS.java
diff options
context:
space:
mode:
authorYuuta Liang <yuutaw@student.cs.ubc.ca>2023-10-26 05:00:12 +0800
committerYuuta Liang <yuutaw@student.cs.ubc.ca>2023-10-26 05:00:12 +0800
commit578b7d1db256d9a582cef45ae5d13d858a977416 (patch)
treeb856cc5af32a0d649321f501f2966d013cade6c0 /src/main/persistence/FS.java
parentf73bca3372a31f360d894dcbe8580cef779af739 (diff)
downloadjca-578b7d1db256d9a582cef45ae5d13d858a977416.tar
jca-578b7d1db256d9a582cef45ae5d13d858a977416.tar.gz
jca-578b7d1db256d9a582cef45ae5d13d858a977416.tar.bz2
jca-578b7d1db256d9a582cef45ae5d13d858a977416.zip
Add persistence
Signed-off-by: Yuuta Liang <yuutaw@student.cs.ubc.ca>
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();
+ }
+}