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.");
}
}