-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathJsonConfigFile.java
More file actions
82 lines (67 loc) · 2.49 KB
/
JsonConfigFile.java
File metadata and controls
82 lines (67 loc) · 2.49 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package me.lokka30.microlib.files;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import org.bukkit.plugin.Plugin;
public class JsonConfigFile {
private static final Gson GSON = (new GsonBuilder()).setPrettyPrinting().create();
private final Plugin plugin;
private final File file;
private final Map<String, Object> values;
private final BufferedReader reader;
public JsonConfigFile(Plugin plugin, File file) throws IOException {
this.values = new HashMap();
this.plugin = plugin;
this.file = file;
this.reader = Files.newBufferedReader(this.getPath());
}
public JsonConfigFile(Plugin plugin, String name) throws IOException {
this(plugin, new File(plugin.getDataFolder(), name));
}
public BufferedReader getReader() {
return this.reader;
}
public Map<String, Object> getValues() {
return this.values;
}
public Object get(String key) throws ClassCastException, NullPointerException {
return this.getValues().get(key);
}
public Object set(String key, Object value) throws UnsupportedOperationException, ClassCastException, NullPointerException, IllegalArgumentException {
return this.getValues().put(key, value);
}
public File getFile() {
return this.file;
}
public String getName() {
return this.getFile().getName();
}
public Path getPath() {
return this.getFile().toPath();
}
private void createIfNotExists() throws IOException {
if (!this.getFile().exists() || this.getFile().isDirectory()) {
try {
this.plugin.saveResource(this.getName(), false);
} catch (IllegalArgumentException var2) {
if(!this.getFile().createNewFile()) throw new IllegalArgumentException("Unable to create new JSON file!", var2);
}
}
}
public void load() throws IOException {
this.createIfNotExists();
this.getValues().putAll((Map)GSON.fromJson(this.getReader(), this.getValues().getClass()));
}
public void save() throws IOException {
String json = GSON.toJson(this.getValues());
Files.write(this.getPath(), Collections.singletonList(json), StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING, StandardOpenOption.WRITE);
}
}