Reputation: 69
I'm currently working on a java project with GUI. I have two forms. One for SignUp and one for LogIn. The SignUp form creates a 'Client' or 'Employee' object based on user input and stores it in a '.ser' file. For my LogIn, I want to deserialize this file by storing the objects in an ArrayList and search for the email and password in each object from that ArrayList. If they exist, the login should be successful. However, my code is only reading the first object in the File and not all of them.
Here's my simplified code.
//Code for Writing to File. Client Object is created through user input in GUI
try{
Address a1=new Address(Integer.parseInt(houseNumberField.getText()),Integer.parseInt(streetNumberField.getText()),cityField.getText(),provinceField.getText());
Client c1=new Client(firstNameField.getText(),lastNameField.getText(),emailField.getText(),passwordField.getText(),Float.parseFloat(phoneField.getText()),Float.parseFloat(CNICField.getText()),a1);
OutputStream out=null;
ObjectOutputStream outputStream=null;
FileOutputStream fileOut=null;
try
{
fileOut=new FileOutputStream("ClientList.ser",true);
outputStream=new ObjectOutputStream(fileOut);
outputStream.writeObject(c1);
JOptionPane.showMessageDialog (null,"record saved","Information",JOptionPane.INFORMATION_MESSAGE);
}
catch(IOException e)
{
System.out.println("Error while opening file");
}
finally {
try {
if(outputStream != null && fileOut!=null) {
outputStream.close();
fileOut.close();
}
}
catch (IOException e)
{
System.out.println("IO Exception while closing file");
}
}
Code for Reading:
try{
ObjectInputStream x = new ObjectInputStream(new FileInputStream("EmployeeList.ser"));
while(true){
try{
Employee a=(Employee) x.readObject();
System.out.println(a);
e1.add(a);
}
catch(EOFException e)
{
e.printStackTrace();
break;
}
}
}
catch(FileNotFoundException e)
{
} catch (IOException ex) {
return ;
} catch (ClassNotFoundException ex) {
Logger.getLogger(loginGUI.class.getName()).log(Level.SEVERE, null, ex);
}
It's only outputting the first Object in the file.
Upvotes: 0
Views: 41
Reputation: 5213
outputStream.writeObject()
will replace previously written objects.
One possible solution is adding them to a container class with a lists of Client/Employee objects and serialize/deserialize this container class instead.
Upvotes: 1