Serialization: Appending to Object Files in Java

2k Views Asked by At

I recently made a serial file for the users. Which I read from when a user tries to log in. And add users to it if a new user registers. But whenever I add a new user the previous record that I added is deleted. Is there a way to append objects to serial files? P.S Im using objects of users which contain username, password, role (instructor or student) and a score (int) variable.

public static void addRecordStudent(String userName, String password, String role, int score)
{
    openFile();
    try
    {
        // create new record; this example assumes valid input
        User usr = new User(userName, password, role, score);
        // serialize record object into file
        output.writeObject(usr);
    }
    catch (NoSuchElementException elementException)
    {
        System.err.println("Invalid input. Please try again.");
    }
    catch (IOException ioException)
    {
        System.err.println("Error writing to file. Terminating.");
    }
    closeFile();
}

 public static void openFile()
{
    try
    {
        output = new ObjectOutputStream(Files.newOutputStream(Paths.get("users.ser")));
    }
    catch (IOException ioException)
    {
        System.err.println("Error opening file. Terminating.");
        System.exit(1); // terminate the program
    }
}

public static void closeFile()
{
    try
    {
        if (output != null)
        output.close();
    }
    catch (IOException ioException)
    {
        System.err.println("Error closing file. Terminating.");
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

You have to explicitly choose to append to file - otherwise old content will be replaced:

Files.newOutputStream(file, StandardOpenOption.APPEND)

In addition to that, every time you create new ObjectOutputStream new stream is started. You won't be able to read them back using single ObjectInputStream. You can avoid that using this trick

If the file is not too large, it might be a better idea to read all existing objects and then write back existing and new objects using single ObjectOutputStream.