Read multiple objects in Java serialized file

Asked

Viewed 2,276 times

1

I have a file Produtos.ser where several objects of the type were recorded Objeto.
In the code method below, I wish to retrieve all objects from the file and store in an Arraylist list.

However, it adds in Arraylist only the first object. Some help?

public ArrayList<Produto> recuperarProdutos(){
    ArrayList<Produto> produtos = new ArrayList<>();
    Produto p = new Produto();

    ObjectInputStream leitorObj = null;
    FileInputStream leitorArquivo = null;
    try {
        leitorArquivo = new FileInputStream("files\\Produtos.ser");
        leitorObj = new ObjectInputStream(leitorArquivo);
        p = (Produto)leitorObj.readObject();
        produtos.add(p);
    } catch(EOFException e) {
    try {
        leitorArquivo.close();
    } catch (IOException ex) {
        System.out.println(ex.getMessage());
    }
    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    } finally {
        try {
            if (leitorArquivo != null) leitorArquivo.close();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    return produtos;
}
  • There is only one item in the list produtos because it gives only one add in it.

1 answer

2


Try to read it as follows:

while(true){
   try{
     p = (Produto)leitorObj.readObject();
     produtos.add(p);
   catch(Exception e){
     break;
   }
}
return produtos;

I imagine this should solve your problem. I’m basing myself on in that reply. That’s when you don’t know how many objects you have, what I advise you to do is save the number of records and replace the while(true) for for(int i = 0; i < numObjetos; i++), there the try\catch becomes unnecessary.

  • Java did not recognize this class Endofstremsignal nor gave hint of Import, tried to replace by null, tbm did not work

  • I’ll edit my answer, to suit you.

  • It would be good if you store the error in a log file, or check the state of the buffer to see if there is something available before trying to read from the stream, or at least use catch(Ioexception) instead of catch(Exception).

Browser other questions tagged

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