How do I write multiple objects to the serializable file and read them when the program is used again?

Udit Chugh picture Udit Chugh · May 3, 2015 · Viewed 24.3k times · Source

I want to maintain database of users of a Bank for my project. I am able to save the number of users in one serializable file. But when I try to save the user to database it adds only the latest one to database.

Below is the sneak peak of code which writes the objects:

if(e.getSource()==submit) {
            if(uFName != null && uLName != null && uInitialDeposit !=0) {
                if(uAccountType=="Savings") {
                    Random randomGenerator = new Random();
                    //Gets the number of users from file if file exists
                    File f = new File(fileNameAdmin);
                    if(f.exists() && !f.isDirectory()) {
                        admin=db.readFromAdminDatabase();
                    }
                    u[admin.numberOfUsers]= new User();
                    u[admin.numberOfUsers].fName=uFName;
                    u[admin.numberOfUsers].lName=uLName;
                    u[admin.numberOfUsers].initalDeposit=uInitialDeposit;
                    u[admin.numberOfUsers].interestRate=uInterestRate;
                    u[admin.numberOfUsers].accountType="Saving";
                    u[admin.numberOfUsers].accountNumber=690000+admin.numberOfSavingsAccount;

                    //Generates a 4 digit random number which will be used as ATM pin
                    u[admin.numberOfUsers].atmPin=randomGenerator.nextInt(9999-1000)+1000;

                    //A savings account will be created 
                    sa[admin.numberOfSavingsAccount]=new SavingsAccount(u[admin.numberOfUsers].accountNumber,u[admin.numberOfUsers].fName,u[admin.numberOfUsers].lName,
                            u[admin.numberOfUsers].initalDeposit,
                            u[admin.numberOfUsers].interestRate);
                    u[admin.numberOfUsers].sa=sa[admin.numberOfSavingsAccount];
                    System.out.println(u[admin.numberOfUsers].sa.balance);
                    JOptionPane.showMessageDialog(submit,"Congratulations! You are now a member of Symbiosis Bank."
                            + "\nYour account number is "+u[admin.numberOfUsers].accountNumber
                            +" and your ATM Pin is "+u[admin.numberOfUsers].atmPin,"Account Created",JOptionPane.INFORMATION_MESSAGE);
                    try {

                        //for(int j = 0; j<admin.numberOfUsers; j++)

                        db.addUserToDatabase(u[admin.numberOfUsers]);
                        admin.numberOfSavingsAccount++;
                        admin.numberOfUsers++;
                        db.updateAdminDatabase(admin);
                        dispose();
                        setVisible(false);
                        //Welcome welcome = new Welcome();
                        //welcome.setVisible(true);
                        InitialInput back = new InitialInput();
                        back.setVisible(true);

                    } catch (Exception e1) {
                        e1.printStackTrace();
                    }
                }
            }

The database class which has functions to write to database:

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Database implements Serializable {
    String fileName = System.getProperty("user.home")+"/db.ser";
    String fileNameAdmin = System.getProperty("user.home")+"/admindb.ser";
    public void addUserToDatabase(User u){

        FileOutputStream fos;
        try {
            fos = new FileOutputStream(fileName);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(u);
            oos.close();
            }
        catch(Exception e) {
            e.printStackTrace();
        }
    }
    @SuppressWarnings("finally")
    public User readFromUserDatabase() {
        FileInputStream fis;
        User temp = null;
        try {
            fis = new FileInputStream(fileName);
            ObjectInputStream ois = new ObjectInputStream(fis);
            temp = (User)ois.readObject();
            //System.out.println(temp.fName);
            ois.close();

        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            return temp;
        }
    }

    public void updateAdminDatabase(Administrator admin) {
            FileOutputStream fos;
            try {
                fos = new FileOutputStream(fileNameAdmin);
                ObjectOutputStream oos = new ObjectOutputStream(fos);
                oos.writeObject(admin);
                oos.close();
                }
            catch(Exception e) {
                e.printStackTrace();
            }
    }
    @SuppressWarnings("finally")
    public Administrator readFromAdminDatabase() {
        FileInputStream fis;
        Administrator temp = null;
        try {
            fis = new FileInputStream(fileNameAdmin);
            ObjectInputStream ois = new ObjectInputStream(fis);
            temp = (Administrator)ois.readObject();
            //System.out.println(temp.fName);
            ois.close();

        }
        catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            return temp;
        }
    }


}

The code which is trying to read the database:

public void actionPerformed(ActionEvent e) {
if(e.getSource()==deposit) {
    //Ask the amount to deposit
    int userAmountToDeposit;
    try {
        for(int i = 0; i<=admin.numberOfUsers; i++) {
            u[i] = db.readFromUserDatabase();
            System.out.println(u[i].accountNumber);

        }
        for(int j =0; j<=admin.numberOfUsers; j++) {
            if(u[j].accountNumber==userAccountNumber) {
                if(u[j].atmPin==userPin) {
                u[j].accountBalance=u[j].sa.balance;
                u[j].sa.deposit(10);
                u[j].accountBalance=u[j].sa.balance;
                System.out.println(u[j].accountBalance);
                }
            }
        }
    }

Answer

Mohan Raj picture Mohan Raj · May 4, 2015

Inorder to write and read multiple objects please try as below

Writing multiple object into List

    WriteObject wo=new WriteObject(20, "Mohan");
    WriteObject wo1=new WriteObject(21, "Mohanraj");

    ArrayList<WriteObject> woi=new ArrayList<>();
    try {
        FileOutputStream fop=new FileOutputStream("c://object.ser");
        ObjectOutputStream oos=new ObjectOutputStream(fop);
        woi.add(wo);
        woi.add(wo1);
        oos.writeObject(woi);

    } catch NotFoundException e) {
}

Reading all objects from file

 try {
        FileInputStream fis=new FileInputStream("C://object.ser");
        ObjectInputStream ois=new ObjectInputStream(fis);
        WriteObject wo=null;
        WriteObject[] woj=new WriteObject[5];

        ArrayList<WriteObject> woi=new ArrayList<>();
        woi=(ArrayList<WriteObject>)ois.readObject();

        for(int i=0;i<woi.size();i++){
            woi.get(i).getvalues();
        }

Here getvalues() is method present in Writeobject class. Follow the same mechanism for your code snippet