0

I'm trying to write ArrayList to a file, and then read a random string from the ArrayList. In the code, I'm trying to output at least the entire ArrayList from the file (in order to select a random one later), but an empty string is obtained on the output.

Serialization:

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());
        }
    }

deserialization:

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;
    } 

User class:

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;
    }
 
}
2
  • what language is it? Java? C#?
    – MrHutnik
    Commented Aug 16, 2023 at 14:08
  • @MrHutnik, this is java
    – AlexSmith
    Commented Aug 17, 2023 at 4:21

0