java 如何将多个对象写入可序列化文件并在程序再次使用时读取它们?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30013292/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 16:18:29  来源:igfitidea点击:

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

javaserializationdeserializationobjectinputstreamobjectoutputstream

提问by Udit Chugh

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

回答by Mohan Raj

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

这里 getvalues() 是存在于 Writeobject 类中的方法。对您的代码片段遵循相同的机制

回答by Blue Like

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.

如果您想快速修复它,您可以创建一个列表并首先将您的对象存储在列表中(可能是 ArrayList 或 List),然后将此列表保存在您的文件中。那是不错的方法。确保您的对象是可序列化的。

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

下面,listeVoitures是一个静态变量,它将包含我将从文件中检索的所有对象。

public static void saveVehiculeInFile(ArrayList vehiculeList) {

公共静态无效 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();
            }
        }
    }
}