Newer
Older
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
83
84
85
86
87
88
89
package org.josast.databaseSync.config;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.logging.Logger;
import org.apache.commons.io.IOUtils;
import org.json.JSONException;
import org.json.JSONObject;
public class ManageJSonConfigFile {
private static Logger appLogger = Logger.getLogger("AmsatLogger");
private String configRepository = "config";
private String configName = "Data.json";
public int SaveConfigFile(Object bean) {
ManageFolder mn = new ManageFolder(configRepository);
mn.createdDirectories();
Path filepath = Paths.get(mn.getRepositoryPath() + "\\"+configName);
int erreur = 0;
JSONObject jasonObject = new JSONObject(bean);
try {
if (!Files.exists(filepath)) {
Files.createFile(filepath);
Files.writeString(filepath, " " + "\r\n", StandardOpenOption.CREATE);
}
Files.writeString(filepath, jasonObject.toString() + "\r\n", StandardOpenOption.CREATE);
if (Files.size(filepath) < 10) {
appLogger.severe("file not created ");
erreur = -1;
}
} catch (IOException e) {
appLogger.severe(e.toString());
erreur = -1;
}
return erreur;
}
public Object readJson(Object object )
{
Object tempobject = null;
String RepositoryPath = System.getProperty("user.dir") + "\\"+configRepository;
System.out.println(RepositoryPath);
Path filepath = Paths.get(RepositoryPath + "\\"+configName);
try {
InputStream is = Files.newInputStream(filepath);
String text = IOUtils.toString(is, "UTF-8");
JSONObject myJsonObject = new JSONObject(text);
tempobject = toBean(myJsonObject, object);
} catch (IOException | JSONException e) {
e.printStackTrace();
appLogger.severe("Erreor reading json file"+filepath.getFileName());
}
return tempobject;
}
public static Object toBean(JSONObject jobject, Object object) {
for (Field field : object.getClass().getDeclaredFields()) {
try {
field.set(object, jobject.getString(field.getName()));
} catch (IllegalArgumentException | IllegalAccessException | JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return object;
}
}