Làm cách nào để data vẫn tồn tại khi thêm mới

public void saveFileUser(User user) {
        JSONObject userJSON = new JSONObject();
        userJSON.put("id", user.getId());
        userJSON.put("username", user.getUsername());
        userJSON.put("password", user.getPassword());
        userJSON.put("role", user.getRoles().getName());
        JSONObject usersJSON = new JSONObject();
        usersJSON.put("user", userJSON);
        JSONArray userList = new JSONArray();
        userList.add(usersJSON);
        try (FileWriter file = new FileWriter("User.json")) {
            file.write(userList.toJSONString());
            file.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

Khi mình thêm 1 user mới thì user có sẵn trong file bị xóa đi nên làm cách nào để giữ user cũ và thêm 1 user mới

Bạn tìm hiểu write file với chế độ append nhé.
Còn về đoạn code trên có nhiều phần xử lý ko cần thiết. Ví dụ đoạn này:

        JSONObject usersJSON = new JSONObject();
        usersJSON.put("user", userJSON);
        JSONArray userList = new JSONArray();
        userList.add(usersJSON);

Sao không write thẳng userJSON vào luôn, add vào list để làm gì

2 Likes

Đúng là vậy, nhưng không phải vậy, JSON là dữ liệu có cú pháp và cấu trúc. Nếu ý bạn @Nguyen_Tuan_Khai_Kha muốn thêm 1 người dùng mới vào mảng JSON thì trước hết phải đọc ra hết rồi thêm mới sau cùng là ghi vào tập tin.

4 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?