【JavaFX】JDK11 基于Gson、hutool、Jackson持久化存储实体类数据的解决方案 (读取、追加、去重、写入json对象)
public class JsonFileServiceImpl implements JsonFileService {
//模板类文件BASE路径
public static final String TEMPLATE_PATH = "src/main/resources/json/";
public static void main(String[] args) {
/* String jsonString = "[{\"name\":\"Alice\",\"age\":25},{\"name\":\"Bob\",\"age\":30},{\"name\":\"Alice\",\"age\":25}]";
JsonArray jsonArray = new JsonParser().parse(jsonString).getAsJsonArray();
JsonFileServiceImpl jsonFileService = new JsonFileServiceImpl();
String res = (jsonArray, "name");
(res);*/
}
@Override
public ObservableList<SftpClient> readJsonFile(String groupName) throws IOException {
File file = null;
//初始化 ObservableList ,不能用 new ObservableList() 进行初始化
ObservableList<SftpClient> clients = FXCollections.observableArrayList();
try {
file = new File(TEMPLATE_PATH + groupName + ".json");
//直接创建该对象即可调用相关方法
ObjectMapper mapper = new ObjectMapper();
SftpClient[] sftpClients = mapper.readValue(file, SftpClient[].class);
String content = FileUtils.readFileToString(file, "UTF-8");
clients.addAll(Arrays.asList(sftpClients));
} catch (Exception e) {
Alert fail_alert = new Alert(Alert.AlertType.ERROR); // 创建一个消息对话框
fail_alert.setHeaderText("文件内容为空,或该组别json文件字段映射不匹配,无法获取Json对象,请先为该组别创建连接。"); // 设置对话框的头部文本
// 设置对话框的内容文本
fail_alert.setContentText(e.toString());
// 显示对话框
fail_alert.show();
}
return clients;
}
@Override
public void createClientJsonFile(String groupName, SftpClient sftpClient) throws IOException {
//如果用户不选择任何分组,系统将添加到默认分组中
if (groupName == null) {
groupName = "默认分组";
sftpClient.setGroup(groupName);
}
File filePath = new File(TEMPLATE_PATH + groupName + ".json");
//创建JsonParser对象
JsonParser parser = new JsonParser();
//从文件中加载JSON内容并转换为JsonElement对象
filePath.createNewFile();
JsonElement root = parser.parse(new FileReader(filePath));
//如果根元素是JSON数组类型
if (root instanceof JsonArray) {
//获取JSON数组
JsonArray array = root.getAsJsonArray();
//创建GSON对象
Gson gson = new GsonBuilder().setPrettyPrinting().create();
//插入对象的各个属性,可以自定义。
JsonObject objToInsert = new JsonObject();
objToInsert.addProperty("group", sftpClient.getGroup());
objToInsert.addProperty("name", sftpClient.getName());
objToInsert.addProperty("host", sftpClient.getHost());
objToInsert.addProperty("port", sftpClient.getPort());
objToInsert.addProperty("username", sftpClient.getUsername());
objToInsert.addProperty("password", sftpClient.getPassword());
//在数组尾部插入新的JSON对象
array.add(objToInsert);
//将更新后的JSON数组转换为字符串
String updatedContent = jsonArrayFilterByAttribute(array, "host");
//写入更新后的JSON内容到原始文件
try (FileWriter writer = new FileWriter(filePath)) {
writer.write(updatedContent);
// 创建一个消息对话框
Alert success_alert = new Alert(Alert.AlertType.INFORMATION);
success_alert.setHeaderText("写入" + filePath + "成功!"); // 设置对话框的头部文本
// 显示对话框
success_alert.show();
System.out.println();
} catch (IOException e) {
System.out.println("Error writing to the file.");
e.printStackTrace();
}
} else {
// 创建一个空的JSON数组对象
JSONArray jsonArr = new JSONArray();
FileWriter writer = new FileWriter(filePath);
//创建FileWriter对象
writer.write(jsonArr.toString());
//将JSON数组转换为字符串后写入文件
//关闭writer流
writer.close();
System.out.println("已成功创建并写入空的JSON数组到文件!");
}
}
@Override
public boolean checkIfFileIsNotEmpty(String group) throws IOException {
BufferedReader reader = null;
File file = new File(TEMPLATE_PATH + group + ".json");
if (!file.exists()) {
System.out.println("Invalid directory path:" + file.getName());
return false;
}
try {
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
while ((reader.readLine()) != null) {
}
return true;
} catch (IOException e) {
return false;
} finally {
if (reader != null) {
reader.close();
}
}
}
@Override
public ObservableList<String> getFileList() {
String suffixName = ".json"; // 设置指定尾部字符
ObservableList<String> fileList = FXCollections.observableArrayList();
//设置指定目录文件
File directory = new File(TEMPLATE_PATH);
if (directory.exists()) {
File[] files = directory.listFiles();
assert files != null;
for (File file : files) {
// 跳过子目录
if (file.isDirectory()) {
continue;
}
//查找目录下为json后缀名的文件
if (file.getName().endsWith(suffixName)) {
int lastDotIndex = file.getName().lastIndexOf(".");
if (lastDotIndex != -1) {
fileList.add(file.getName().substring(0, lastDotIndex));
}
}
}
} else {
System.out.println("指定目录不存在!");
}
return fileList;
}
@Override
public String jsonArrayFilterByAttribute(JsonArray jsonArray, String attribute) {
Set<String> uniqueNames = new HashSet<>();
JsonArray uniqueArray = new JsonArray();
for (int i = 0; i < jsonArray.size(); i++) {
JsonObject jsonObject = jsonArray.get(i).getAsJsonObject();
String name = jsonObject.get(attribute).getAsString();
if (!uniqueNames.contains(name)) {
uniqueNames.add(name);
uniqueArray.add(jsonObject);
}
}
return uniqueArray.toString();
}