简体   繁体   中英

last object serialized gets overwritten

I am writing a program for keeping track of library books. There is an object book that includes a title, sku number, price and quantity. All the books are stored in an Array List. I'm trying to serialize the books and add new books but every time a book is added the last is overwritten.

here is the code below to load objects from save

public static void readSave() {
        
        File stockFile = new File("inventory.txt");
        
        try {
            if(!stockFile.createNewFile() && stockFile.length() != 0) {
                ObjectInputStream objIn = new ObjectInputStream(new FileInputStream(stockFile));
                int size = objIn.readInt();
                
                for(int i = 0; i < size; i++) {
                    Book t = (Book) objIn.readObject();
                    bookList.add(t);
                }
                
                objIn.close();
            }
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }   
    }

here is my save method and it is set to save every time the program executes.

public static void save() {
        File inventoryFile = new File("inventory.txt");
        
        ObjectOutputStream objOut;
        try {
            objOut = new ObjectOutputStream(new FileOutputStream(inventoryFile));
        
            objOut.writeInt(bookList.size());
            Iterator<Book> i = bookList.iterator();
            while(i.hasNext()){
                objOut.writeObject(i.next());
            }
        
            objOut.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

below is my main method which calls these functions

public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    readSave();
                    CampusBookWindow window = new CampusBookWindow();
                    window.frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                save();
            }
        });
    }

我的问题是当我点击添加书籍按钮时,我不会为该项目创建一个新的书籍对象,而是我重新分配了最后一个书籍对象,因此对象最后一个书籍对象从 bookList 数组列表中删除

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM