0

I have written a java program that needs to save a list of an Object I created called User. This is my code for saving and loading the list:

/**
 * Save list to file
 * @param saveList list to be saved
 */
public void saveUsers(List<User> saveList){
            try{
                FileOutputStream fileOut = new FileOutputStream("data/userlist.ser", true);
                OutputStream out = new BufferedOutputStream(fileOut);
                ObjectOutput output = new ObjectOutputStream(out);
                output.writeObject(saveList);;
                out.close();
                fileOut.close();
                output.close();
                for(User u : saveList){
                    System.out.println(u.getUsername());
                }
                System.out.println("List written to file");
            }catch(IOException e){
                e.printStackTrace();
            }
}
/**
 * 
 * @return list of all users in system.
 */
@SuppressWarnings({ "resource", "unchecked" })
public static List<User> loadUsers(){

    try{
        InputStream saveFile = new FileInputStream("data/userlist.ser");
        InputStream buffer = new BufferedInputStream(saveFile);
        ObjectInput input= new ObjectInputStream(buffer);
        LinkedList<User> loadList = (LinkedList<User>) input.readObject();
        System.out.println(loadList.size());
        for(User u : loadList){
            u.reload();
            System.out.println(u.getUsername());
        }
        return loadList;

    }catch(Exception e){
        e.printStackTrace();
    }
    List<User> l = new LinkedList<User>();
    return l;
}

And my code seems to work for save because the output each time it is called shows all the users being added to the list, however on the load it only loads the first User. This is my user class:

public class User implements Serializable{

/**
 * Variables
 */
private transient StringProperty usernameProperty;
private String username;
private List<Album> albums = new LinkedList<Album>();
private List<Photo> photos = new LinkedList<Photo>();;
private List<Tag> tags = new LinkedList<Tag>();;
private static final long serialVersionUID = 1738L;

/**
 * public constructor to create a user
 * @param username
 */
public User(String username){
    this.username = username;
    this.usernameProperty = new SimpleStringProperty(username);
}

And all of my other classes are implementing the Serializable as well. Is there any reason the list is being saved to the file but not loading fully?

7
  • Side note: you're saving any list which could be an ArrayList but when loading assume it's a LinkedList. This might lead to errors. Commented Mar 18, 2016 at 16:07
  • what is the size printed in line System.out.println(loadList.size()); ? Commented Mar 18, 2016 at 16:26
  • It says 1, although When I look at the .ser file I make there seems to be more than one (I can see saved ascii characters) Commented Mar 18, 2016 at 16:37
  • Try clearing the file. Save users again through your code and call loadUsers(). Your file might be having objects other than User list which could be causing this. Commented Mar 18, 2016 at 16:47
  • Ok, I cleared the file and recreated it and commented out all of the parts of the User class except for the string username, I am still having the same problem. The linked List is still only 1 in size when I load it. Commented Mar 18, 2016 at 16:52

3 Answers 3

1

I figured out the answer, apparently every time I was calling the save class, I was not overwritting the file but appending to it, so I was only reading the first array list being stored, pretty simple fix I just added the lines

                File file = new File("data/userlist.ser");
                file.delete();

to the beginning of my saveUsers function to clear the file, now it works perfectly.

Sign up to request clarification or add additional context in comments.

Comments

0

Change LinkedList loadList = (LinkedList) input.readObject(); to ArrayList. Edit the file userlist.ser delete the contents or create a new file and use it in your code. It works fine for me.

Comments

0

Finding the error in your code is for me more complex than testing my own solution, so I have made a quick model for you, using a the same classes you use, but using a custom class (car) for this...

the Code:

public static void main(String[] args) throws Exception {
        final Car c0 = new Car("bmw", 1990);
        final Car c1 = new Car("VW", 2000);
        final Car c2 = new Car("Audi", 2010);
        final Car c3 = new Car("Mini", 2015);
        final LinkedList<Car> lisCar = new LinkedList<Car>();
        lisCar.add(c0);
        lisCar.add(c1);
        lisCar.add(c2);
        lisCar.add(c3);
        serialThis(lisCar);
        deserializeFileToList();
    }

Serialize to file:

private static void serialThis(LinkedList<Car> lisCar) throws Exception {
    final FileOutputStream fos = new FileOutputStream("serialized.txt");
    final ObjectOutputStream oos = new ObjectOutputStream(fos);
    oos.writeObject(lisCar);
    oos.close();
}

Deserialize from file:

private static void deserializeFileToList() throws Exception {
    final FileInputStream fis = new FileInputStream("serialized.txt");
    final ObjectInputStream ois = new ObjectInputStream(fis);
    final LinkedList<Car> ds = (LinkedList<Car>) ois.readObject();
    ois.close();

    System.out.println(ds);
}

The Car class:

private static final long serialVersionUID = -427928246789764110L;

    @Override
    public String toString() {
        return "Car [year=" + year + ", type=" + type + "]";
    }

    private final int year;
    private final String type;

    public Car(String type, int year) {
        this.type = type;
        this.year = year;
    }

4 Comments

Ok I tried this but I am getting a streamcorruptedexception, do I also need to save the users one by one?
No only the Object and Buffered Classes
I update my answer, and tested with a dummy Car class, it is working on my environment, please give a try and let me know...
Ok I found the issue it was actually an issue saving the file correctly.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.