14

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);
                }
            }
        }
    }
Udit Chugh
  • 621
  • 1
  • 7
  • 22
  • 2
    Personal grip: Serialisation is a poor choice for the long term storage of objects, it simply wasn't designed for it. If a single user database is out of the question, then I would suggest having a look at [JAXB](https://docs.oracle.com/javase/tutorial/jaxb/intro/) instead – MadProgrammer May 03 '15 at 11:31
  • Unfortunately I have came too far to switch to JAXB. It would be great if you could help me with this without JAXB. @MadProgrammer – Udit Chugh May 03 '15 at 11:33
  • 3
    Usually, you should use a real database for long term storage of objects, as doing serialization like this will become unmaintainable as your program grows. There are some nice implementations of Sqlite for java, which will give you a database in a single file. But if it's too late to implement a proper database, that's understandable. – JonasCz May 03 '15 at 11:34
  • I can really understand the disadvantage of Serialization. But the problem is it will be really hard to switch to any other concept like JAXB as I have to submit my project tomorrow. And as far as long term usage is concerned, this program won't be used in long term. @JonasCz – Udit Chugh May 03 '15 at 11:36
  • 1
    Your code creates one file and writes one object to it. If you want to write multiple objects to one file, just do that. Unclear what the difficulty with that is. – user207421 May 03 '15 at 12:16

2 Answers2

21

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

user207421
  • 289,834
  • 37
  • 266
  • 440
Mohan Raj
  • 1,028
  • 9
  • 16
2

If you want to fix it rapidly, you can create a list and store first and foremost your objects in the list (may be ArrayList or List), and then you'll save this list on your file. That is the nice method. Make sure that your objects are serializable.

below, listeVoitures is a stactic variable that will contain all object that i'm going to retrive from file.

public static void saveVehiculeInFile(ArrayList vehiculeList) {

    ObjectOutputStream ous = null;
    //ArrayList<Vehicule> listVehiculeToSave = new ArrayList<>();

    try {
        ous = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(new File("garage.txt"))));

            try {

                ous.writeObject(vehiculeList);
                System.out.println("\t=====> Les vehicules *** ont été ajouter dans le garage.");

            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }       

    } catch (FileNotFoundException e) {

        e.printStackTrace();
    } catch (IOException e) {

        e.printStackTrace();
    } finally {

        if (ous != null) {
            try {
                ous.close();
            } catch (IOException e) {

                e.printStackTrace();
            }
        }
    }


}

This method below is for retrive data from file

public static void readVehiculeFromFile() {

    ObjectInputStream ins = null;
    ArrayList<Vehicule>  v = null;

    try {
        ins = new ObjectInputStream(new BufferedInputStream(new FileInputStream(new File("PoweredGarage.txt"))));

        try {
            v = (ArrayList<Vehicule>)ins.readObject();

        } catch (ClassNotFoundException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

            for (Vehicule vehicule : v) {
                listeVoitures.add(vehicule);
            }


    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally {
        if (ins != null) {
            try {
                ins.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
Blue Like
  • 41
  • 3