How to read and save an object to a java file

Asked

Viewed 480 times

1

Personal What can I do to read an object from a file correctly? What is the problem with my code?

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.util.ArrayList;

import java.io.Serializable;

public class Cliente implements Serializable{

    private static final long serialVersionUID = 1L;
    private int codigo;
    private String nome;
    private Endereco endereco;
    private int telefone;

    public int getCodigo() {
        return codigo;
    }
    public void setCodigo(int codigo) {
        this.codigo = codigo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public Endereco getEndereco() {
        return endereco;
    }
    public void setEndereco(Endereco endereco) {
        this.endereco = endereco;
    }
    public int getTelefone() {
        return telefone;
    }
    public void setTelefone(int telefone) {
        if (telefone > 0) {
            this.telefone = telefone;
        }
    }

    public static void escrever(Cliente cliente) {
        File arquivo = null;
        ObjectOutputStream obj = null;
        try {
            arquivo = new File("./bin/clientes.obj");
            obj = new ObjectOutputStream(new FileOutputStream(arquivo, true));
            obj.writeObject(cliente);
            obj.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static ArrayList<Cliente> ler() {
        FileInputStream arquivo = null;
        ArrayList<Cliente> clientes = new ArrayList<Cliente>();
        Cliente cliente = null;
        ObjectInputStream obj = null;
        try {
            arquivo = new FileInputStream("./bin/clientes.obj");
            obj = new ObjectInputStream(arquivo);
            do {
                cliente = (Cliente) obj.readObject();
                if (cliente != null)
                    clientes.add(cliente);
           } while (cliente != null);
            arquivo.close();
            obj.close();
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } 
        return clientes;
    }

    public static void main(String[] args) {
        Cliente cliente = new Cliente();
        ArrayList<Cliente> clientes = new ArrayList<Cliente>();

        cliente.setNome("Gabriel");
        Cliente.escrever(cliente);
        System.out.println("Ok");

        clientes = Cliente.ler();

        for (Cliente c: clientes) {
            System.out.printf("Cliente: %s\n", c.getNome());
        }
    }

}

Exit:

OK

Error:

java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1600)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:430)
at Cliente.ler(Cliente.java:70)
at Cliente.main(Cliente.java:90)

Client: Gabriel

  • As the error indicates, what is calling exception is the readObject method.

1 answer

0


Your error has to do with the way you wrote objects to the file.

There can be no append of objects in a stream opened after the first stream for the stream will be corrupt.

Is writing Client and closes the stream, this will make a new header is added to your file (this header is for the reading process by Java methods).

  • If you want to write Client to Client using this method has to cause Stream to be closed only when you have written all the clients you want to write.

  • Another solution would be to read the Customers from the file, delete everything from the file and write again to the file with the addition of the new client.

  • The best solution is to keep the previous header and only write the objects you want to add.

There is a solution referenced in Stackoverflow

Browser other questions tagged

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