Search code examples
javasetobjectinputstream

How to read file using ObjectInputStream and add objects to HashSet?


I am trying to read file and add all objects into HashSet but I have an error "User cannot be cast to java.util.HashSet". How can I fix it?

private void readFromFile(String file){
    Set<User> users = new HashSet<User>();
    try(FileInputStream fileInputStream = new FileInputStream(file)){
        ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);

        users = (HashSet) objectInputStream.readObject();

        System.out.println(users);
        objectInputStream.close();

    } catch (IOException | ClassNotFoundException e) {
        e.printStackTrace();
    }
}

And how can I use serialize more than one object into file? For example(I am using Scanner and trying to input name and surname), when I do it my file has only one object.


Solution

  • First, as @Nicholas K mentioned,

    because you wrote User objects into the stream, then you should read User objects after.

    And as you said

    When I tried it I had only one object there but my file includes more than three users

    You got one object because you read only one object.

    Calling

    User user = (User) objectInputStream.readObject();

    reads only one user (if exists). Calling read() once more and you will get your second object (again, if it exists).

    So all you need to do is this:

    private void readFromFile(String file){
            Set<User> users = new HashSet<User>();
            try(FileInputStream fileInputStream = new FileInputStream(file)){
                ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
    
                while (true) {
                    User user = (User) objectInputStream.readObject();
                    users.add(user);    
                }
    
            } catch(EOFException e){
                // This exception is raised because the whole file was read.
                // So print the users in the set.
    
                for (User user : users) {
                    System.out.println(user);
                }
    
            } catch (IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }finally{
                // Never forget to close the stream after you're done
                if (objectInputStream!=null) {
                    objectInputStream.close();
                }
        }