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(); } }