aboutsummaryrefslogtreecommitdiff
path: root/src/main/persistence/FS.java
blob: 3b5222dce8addea9edddba190aa055232d886bd6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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();
    }
}