Read ArrayList that is serialized

0

I create and instantiate student-type objects (abstract class), and add them to the array. Soon after this, the serialization of the same one is made. How can I deserialize this array, and print the toString of it, and use other functionality, such as doing a search 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);
    }
}
    
asked by anonymous 27.11.2017 / 01:14

1 answer

1

Hello, you have to assign to an object of the same type it was before serializing as below and using the readObject() method. I strongly recommend the use of try-resources to close your features 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);
}
    
27.11.2017 / 17:46