序列化和反序列化列表

Serialization and deserialization a list

提问人:AlexSmith 提问时间:8/16/2023 更新时间:8/16/2023 访问量:22

问:

我正在尝试将 ArrayList 写入文件,然后从 ArrayList 中读取一个随机字符串。 在代码中,我尝试从文件中至少输出整个 ArrayList(以便稍后选择一个随机的),但在输出上获得一个空字符串。

序列化:

public void oStream(User user) {
 
        ArrayList<User> people = new ArrayList<User>();
        people.add(user);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("person.txt", true))) {
            oos.writeObject(people);
        } catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

反序列化:

public ArrayList<User> iStream() {
 
        ArrayList<User> people = new ArrayList<>();
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("person.txt"))) {
             for (User p : people)
                  people.add(p);
             people = (ArrayList<User>) ois.readObject();
        }
             catch (IOException | ClassNotFoundException e) {
                   throw new RuntimeException(e);
        }
        return people;
    } 

用户类:

public class User implements Serializable {
 
    private String login;
    private String password;
    private String email;
    private String date;
 
    public User(String login, String password, String email, String date) {
        this.login = login;
        this.password = password;
        this.email = email;
        this.date = date;
    }
 
    public User(String login, String password, String email) {
        this.login = login;
        this.password = password;
        this.email = email;
    }
 
    public User() {
    }
 
    public String getLogin() {
        return login;
    }
    public String getPassword() {
        return password;
    }
    public String getEmail() {
        return email;
    }
    public String getDate() {
        return date;
    }
 
    public void setLogin(String login) {
        this.login = login;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public void setDate(String date) {
        this.date = date;
    }
 
}
对象 ArrayList 反序列化

评论

0赞 MrHutnik 8/16/2023
它是什么语言?爪哇岛?C#?
0赞 AlexSmith 8/17/2023
@MrHutnik,这就是 Java

答: 暂无答案