blob: c97e5fdf1c6764a279caf9b20ddb904c7afc5118 (
plain) (
blame)
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 persistance;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class JsonUtils {
/**
* REQUIRES: A valid filepath path, a writeable JSONObject json
* EFFECTS: writes a String to a file
*/
public static void writeToFile(JSONArray json, String path) {
PrintWriter writer;
try {
writer = new PrintWriter(path);
writer.print(json);
writer.close();
} catch (Exception e) {
System.out.printf("Write to file failed with %s", e.toString());
}
}
/**
* REQUIRES: a path to a valid file containing JSONObject-serialized data
* EFFECTS: reads a serialized String into a JSONObject
*/
public static JSONArray readFromFile(String pathString) {
String content;
JSONArray deread;
Path path;
try {
path = Paths.get(pathString);
content = new String(Files.readAllBytes(path));
deread = new JSONArray(content);
} catch (Exception e) {
System.out.println("Read from file failed with %s");
deread = new JSONArray();
}
return deread;
}
}
|