Read Arraylist that is serialized

Asked

Viewed 137 times

0

I create and instantiate objects of the student type (abstract class), and add them in the array. After that, the serialization of the same is done. How can I deserialize this array, and print toString from it, and use other functionality, such as searching by name ?

ArrayList<Aluno> ob = new ArrayList<>();

        Aluno tres = new Aluno_Graduacao("Pedro", "Silva", 2, "Tads", 2015, 10);
        ob.add(tres);

        Aluno o = new Aluno_Graduacao("Stanley", "Henrique", 2, "Tads", 2015, 10);
        ob.add(o);


        Aluno quatro = new Aluno_Graduacao("Costa", "Marcelo", 2, "Tads", 2015, 10);
        ob.add(quatro);



        Aluno dois = new Aluno_Graduacao("Maria", "Silva", 2, "Tads", 2015, 10);

        ob.add(dois);


        try{
            FileOutputStream oo = new FileOutputStream("Arquivo.txt", true);
            ObjectOutputStream oob = new ObjectOutputStream(oo);

            oob.writeObject(ob);
            oob.close();


            FileInputStream ler = new FileInputStream("Arquivo.txt");
            ObjectInputStream lerr = new ObjectInputStream (ler);

            //Aqui é onde nao consigo achar a solucao 
        } catch (FileNotFoundException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
    }
}

1 answer

1

Hello Voce has to assign to an object of the same type it was before serialize conforms to the bottom and use the method readObject(). I strongly recommend using Try-Resources to close your resources automatically.

try(FileInputStream ler = new FileInputStream("Arquivo.txt");
ObjectInputStream lerr = new ObjectInputStream (ler)){

ArrayList<Aluno> listaDeserializada =(ArrayList<Aluno>) lerr.readObject();

} catch (FileNotFoundException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
    Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.