Solucionado (ver solução)
Solucionado
(ver solução)
3
respostas

Ler Vários objetos

Olá pessoal. Estou tentando gravar mais de um objeto em um arquivo binário, até consigo pelo que estou vendo, porém, não estou conseguindo ler. Alguém poderia me dá um luz?


import java.io.Serializable;
import java.time.LocalDate;

public class Cliente implements Serializable {

    private String nome;
    private String cpf;
    private LocalDate nascimento;
    private String endereco;
    private String telefone;

    public Cliente(String nome, String cpf, LocalDate nascimento, String endereco, String telefone) {
        this.nome = nome;
        this.cpf = cpf;
        this.nascimento = nascimento;
        this.endereco = endereco;
        this.telefone = telefone;
    }

    public String getNome() {
        return nome;
    }

    public String getCpf() {
        return cpf;
    }

    public LocalDate getNascimento() {
        return nascimento;
    }

    public String getEndereco() {
        return endereco;
    }

    public String getTelefone() {
        return telefone;
    }

}
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.time.LocalDate;

public class GravarArquivo {

    public static void main(String[] args) throws IOException {


        Cliente c1 = new Cliente("Tiago", "111.111.111-00", 
                LocalDate.of(1111, 11, 11), "Almirante Barroso",
                "11 11111111");

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("Cliente.bin", true));

        oos.writeObject(c1);
        oos.close();

    }

}
import java.io.FileInputStream;
import java.io.ObjectInputStream;

public class LerArquivo {

    public static void main(String[] args) throws Exception {

        ObjectInputStream oos = new ObjectInputStream(new FileInputStream("Cliente.bin"));

        Object obj = null;

        while ((obj = oos.readObject()) != null) {

            System.out.println(((Cliente) obj).getCpf());

        }

        oos.close();

    }

}
Exception in thread "main" java.io.StreamCorruptedException: invalid type code: AC
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1563)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:422)
    at LerArquivo.main(LerArquivo.java:12)
3 respostas

Eu testei seu código aqui e deu certo, consegui ler o arquivo Cliente.bin sem problemas.

Apresentou outro Exception quanto ao loop (EOFException) mas aí é só corrigir o EOF.

Acredito que o problema seja quanto o caminho do arquivo. parecido com esse:

https://cursos.alura.com.br/forum/topico-exception-in-thread-main-java-io-filenotfoundexception-arquivo-txt-29813

Veja se é a mesma coisa, qualquer coisa avisa se não deu certo.

Oi Enzo. Boa noite! Fiz novamente algumas pesquisas e "Consegui", porém, ele deu EOFException.

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class LerArquivo {

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        FileInputStream fis = new FileInputStream("cliente.bin");

        while (true) {
            ObjectInputStream ois = new ObjectInputStream(fis);
            Object o = ois.readObject();
            Cliente c = (Cliente) o;
            System.out.println(c.getCpf());
        }

    }

}

Resultado....

111.111.111-00
211.111.111-00
311.111.111-00
Exception in thread "main" java.io.EOFException
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2624)
    at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:3099)
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:853)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
    at LerArquivo.main(LerArquivo.java:12)
solução!

Consegui!!!! Caso alguém precise está ai...

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class LerArquivo {

    private static FileInputStream fis;

    public static void main(String[] args) throws IOException, ClassNotFoundException {

        fis = new FileInputStream("cliente.bin");

        while(fis.available()>0){
        ObjectInputStream ois = new ObjectInputStream(fis);
        Object object = ois.readObject();
        Cliente cliente = (Cliente) object;
        System.out.println(cliente.getCpf());
        }

    }

}

Resultado....

111.111.111-00
211.111.111-00
311.111.111-00

Quer mergulhar em tecnologia e aprendizagem?

Receba a newsletter que o nosso CEO escreve pessoalmente, com insights do mercado de trabalho, ciência e desenvolvimento de software