-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJsonWriter.java
49 lines (38 loc) · 1.27 KB
/
JsonWriter.java
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
47
48
49
package persistence;
import model.ToDoList;
import org.json.JSONObject;
import java.io.*;
// This class references code from JsonSerializationDemo
// https://github.students.cs.ubc.ca/CPSC210/JsonSerializationDemo.git
// Represents a writer that writes JSON representation of to-do list to file
public class JsonWriter {
private static final int TAB = 4;
private PrintWriter writer;
private final String destination;
// EFFECTS: constructs writer to write to destination file
public JsonWriter(String destination) {
this.destination = destination;
}
// MODIFIES: this
// EFFECTS: opens writer; throws FIleNotFoundException if destination file cannot
// be opened for writing
public void open() throws FileNotFoundException {
writer = new PrintWriter(destination);
}
// MODIFIES: this
// EFFECTS: writes JSON representation of to-do list to file
public void write(ToDoList list) {
JSONObject json = list.toJson();
saveToFile(json.toString(TAB));
}
// MODIFIES: this
// EFFECTS: closes writer
public void close() {
writer.close();
}
// MODIFIES: this
// EFFECTS: writes string to file
private void saveToFile(String json) {
writer.print(json);
}
}