简体   繁体   English

Java:序列化和反序列化ArrayList

[英]Java: Serialize & DeSerialize ArrayList

I have a class Book() , Author() and a class CollectionOfBooks() (where I stock all the books in an ArrayList). 我有一个类Book()Author()和一个CollectionOfBooks()类(在这里我将所有书籍都存放在ArrayList中)。 Then I have my interface where I have a menu where I can add/list/remove/search books. 然后,我在界面上有一个菜单,可以在其中添加/列出/删除/搜索书籍。 Everything works fine. 一切正常。 But, I also want to save my books in a file when I exit the program so when the program ends I call this method( BooksIO() is the class for serialize&deserialize): 但是,我也想在退出程序时将书籍保存在文件中,所以当程序结束时,我调用此方法( BooksIO()是serialize& BooksIO()的类):

public void exitProgram() throws IOException{
        System.out.println("Program shuts down, cya!");
        BooksIO.outputFile(); // to save my books to the file
    }

I am not sure if the books are saved because when I start the program the books don't show up: 我不确定这些书是否已保存,因为启动程序时这些书不会显示:

public static void main(String[] args) throws IOException, ClassNotFoundException {
        UserInterface menu = new UserInterface();
        BooksIO.inputFile(); // get the books from the saved file to the library
        menu.run();
    }

I am not sure what I am doing wrong, can someone help me? 我不确定自己在做什么错,有人可以帮助我吗? The class for Serialize & DeSerialize : 序列化和反序列化的类:

    public class BooksIO {

            public static  void outputFile() throws IOException{
                CollectionOfBooks library = new CollectionOfBooks(); //where the books are saved in an ArrayList
                FileOutputStream fout=null;
                ObjectOutputStream oos=null;
                try{
                    fout = new FileOutputStream ("stefi.ser");
                    oos=new ObjectOutputStream(fout);
                    // I try to save my library to the file
                    oos.writeObject(library.Books); 

                    System.out.println("Serializing successfully completed");

                    for(Book c: library.Books){
                        System.out.println(c.toString());
                    }
                } catch (IOException ex){
                    System.out.println(ex);
                }finally{
                    try{
                        if(fout!=null) fout.close();
                        if(oos!=null) oos.close();
                    } catch (IOException e){

                    }
                }
            }

            public static void inputFile() throws IOException, ClassNotFoundException{

                CollectionOfBooks library = new//where my books are saved in an ArrayList of type Book CollectionOfBooks();//where my books are saved in an ArrayList of type Book
                ObjectInputStream ois = null;
                try{
                    FileInputStream fin = new FileInputStream("stefi.ser");
                    ois = new ObjectInputStream(fin);
                    // try to get my books from the file and save it in the library
                    library.Books  = (ArrayList<Book>)ois.readObject();
                    System.out.println("Deserializing successfully completed");

                    for(Book c: library.Books){
                        System.out.println(c.toString());
                    }

                }catch (ClassNotFoundException e){
                    System.out.println("The class for this type of objects"+
                            "does not exist in this application!");
                    throw e;
                }finally{
                    try{
                        if(ois!=null){
                            ois.close();
                        }
                    }catch (IOException e){

                    }
                }
            }
        }

Right at the top of your outputFile() method, you are initializing a "library" variable to a new (presumably empty) CollectionOfBooks, and then serializing that. 在outputFile()方法的顶部,您正在将“库”变量初始化为新的(可能是空的)CollectionOfBooks,然后对其进行序列化。

What you want to do instead is pass the application's instance of CollectionOfBooks into the outputFile() method, and serialize that. 您要做的是将应用程序的CollectionOfBooks实例传递到outputFile()方法,并对其进行序列化。

Also, while others may disagree, I find Java serialization to be a bit clunky, and it has some odd edge cases that you need to be aware of. 另外,尽管其他人可能不同意,但我发现Java序列化有些笨拙,并且您需要注意一些奇怪的情况。 I personally wouldn't use it unless I had to for some reason - I'd use a JSON serialization library, like perhaps GSon, instead. 除非出于某种原因,我个人不会使用它-我会使用JSON序列化库,例如GSon。

Just guessing because your question does not include a valid MCVE program yet, but it appears that you're reading in the books but not getting them to where they belong, to the main GUI, quite possibly the UserInterface class (we don't no, since you've not shown us). 只是猜测,因为您的问题尚不包含有效的MCVE程序,但您似乎正在阅读这些书,但未将它们带到主GUI的用户界面中,很可能是UserInterface类(我们不,因为您尚未显示我们)。 If so... 如果是这样的话...

Give the UserInterface class a public void updateBooks(CollectionOfBooks books) method, and call this with the updated book collection: 给UserInterface类提供一个public void updateBooks(CollectionOfBooks books)方法,并使用更新的book集合调用此方法:

public void updateBooks(CollectionOfBooks collectionOfBooks) {
    this.collectionOfBooks = collectionOfBooks;
}

Change inputFile to return a CollectionOfBooks object: 更改inputFile以返回CollectionOfBooks对象:

public static CollectionOfBooks inputFile() throws IOException, ClassNotFoundException{
    //...

}

and then return the collection. 然后返回集合。

Then in main you could do: 然后主要可以做:

public static void main(String[] args) throws IOException, ClassNotFoundException {
    UserInterface menu = new UserInterface();
    menu.updateBooks(BooksIO.inputFile()); 
    menu.run();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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