How to read an object from a file?

Asked

Viewed 27 times

-1

Personal when I try to read the objects saved in a file appears the following error message.

Nome: Gabriel
Código: 123
Telefone: 12345678
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.lerArquivoL(Cliente.java:107)
    at Cliente.ler(Cliente.java:91)
    at TesteCliente.main(TesteCliente.java:8)

What do I have to do to remove this invalid type code: AC that he’s reading? The problem is when you’re writing that it goes "garbage" or is in reading that you’re picking up this "garbage" ?

Java cliete.

import java.io.EOFException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.NoSuchElementException;

public class Cliente implements Serializable {
    private static final long serialVersionUID = 1L;
    private static ObjectOutputStream output;
    private static ObjectInputStream input;
    private int codigo;
    private String nome;
    //private Endereco endereco;
    private int telefone;

    public Cliente() {}
    public Cliente(String nome, int codigo, /*Endereco endereco*/ int telefone) {
        this.nome = nome;
        this.codigo = codigo;
        //this.endereco = endereco;
        this.telefone = 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) {
        abrirArquivoE();
        adicionarE(cliente);
        fecharArquivoE();

    }
    private static void abrirArquivoE() {
        try {
            output = new ObjectOutputStream(Files.newOutputStream(Paths.get("./bin/clientes.obj"), StandardOpenOption.CREATE,StandardOpenOption.APPEND));
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void adicionarE(Cliente cliente) {
        try {
            output.reset();
            output.writeObject(cliente);
        }
        catch (NoSuchElementException elementException) {
            elementException.printStackTrace();
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void fecharArquivoE() {
        try {
            if (output != null)
                output.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    public static void ler() {
        abrirArquivoL();
        lerArquivoL();
        fecharArquivoL();
    }
    private static void abrirArquivoL() {
        try {
            input = new ObjectInputStream(Files.newInputStream(Paths.get("./bin/clientes.obj")));
        }
        catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
    private static void lerArquivoL() {
        while (true) {
            try {

                Cliente cliente = (Cliente) input.readObject();
                System.out.printf("Nome: %s\n", cliente.getNome());
                System.out.printf("Código: %d\n", cliente.getCodigo());
                System.out.printf("Telefone: %d\n", cliente.getTelefone());
            }
            catch (EOFException endOfFileException) {
                endOfFileException.printStackTrace();
            }
            catch (ClassNotFoundException classNotFoundException) {
                classNotFoundException.printStackTrace();
            }
            catch (IOException ioException) {
                ioException.printStackTrace();
                break;
            }
        }
    }
    private static void fecharArquivoL() {
        try {
            if (input != null)
                input.close();
        } catch (IOException ioException) {
            ioException.printStackTrace();
        }
    }
}

Class with the main method, Testeclient.java

public class TesteCliente {
    public static void main(String[] args) {
        Cliente.escrever(new Cliente("Gabriel", 123, 12345678));
        Cliente.escrever(new Cliente("Maria", 124, 1234567889));
        Cliente.escrever(new Cliente("Carlos", 125, 1234567890));
        Cliente.escrever(new Cliente("Pedro", 126, 1234567890));

        Cliente.ler();
    }
}

1 answer

0


Hello,

You have to leave Outputstream open while you are writing data, the write method should not open Outputstream, you have to change the logic of your program to create an Outputstream only once and use it for every client you write, got it?

As you call the write method several times will release that exception because the file is the same.

You could create a class for example Archival that opens the file, this class will be responsible for opening close and read the file, the client class only uses it

There in your test you would have something more or less like this

public class TesteCliente {
    public static void main(String[] args) {
        ArquivoUtil.abrirArquivo();
        Cliente.escrever(new Cliente("Gabriel", 123, 12345678));
        Cliente.escrever(new Cliente("Maria", 124, 1234567889));
        Cliente.escrever(new Cliente("Carlos", 125, 1234567890));
        Cliente.escrever(new Cliente("Pedro", 126, 1234567890));

        ArquivoUtil.abrirArquivo().ler();
    }
}

Try to change your code there, anything put again

Browser other questions tagged

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