How to write objects to a file and read these objects

Asked

Viewed 702 times

1

I need to record the created objects in a TXT file and then read the recorded files and show the recorded objects. I searched in several places but I’m not able to solve my problem.

I have a class Client already implementing the Serializable.

package lista7Questao2;

import java.io.*;
import java.util.Scanner;

public class PrincipalClienteQuestao2 {

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

        Scanner sc = new Scanner(System.in);
        String dia,
               mes,
               ano,
               sexo,
               nome = "";
        int age;

        Cliente c = new Cliente();

            try{

            FileOutputStream fileos=  new FileOutputStream("D:\\System 32\\POO\\Lista 7\\Cadastro Clientes.txt");
            ObjectOutputStream obj = new ObjectOutputStream(fileos);

                while (!(nome.equals("fim") || nome.equals("FIM"))){

                System.out.println("Nome: ");
                nome = sc.nextLine();
                if(nome.equals("fim") || nome.equals("FIM")){
                    System.out.println("Programa encerrado.");
                    break;
                }

                System.out.println("dia: ");
                dia = sc.nextLine();

                System.out.println("Mes: ");
                mes = sc.nextLine();

                System.out.println("Ano: ");
                ano = sc.nextLine();

                System.out.println("Sexo: ");
                sexo = sc.nextLine();

                //SETTANDO OS DADOS PARA AS VARIAVEIS
                c.setNome(nome);
                c.setDia(dia);
                c.setMes(mes);
                c.setAno(ano);
                c.setSexo(sexo);

                age = Integer.parseInt(ano);
                int idade = c.calculaIdade(age);

                //GRAVANDO O OBJETO CLIENTE NO ARQUIVO TXT
                obj.writeObject(c);
                //obj.writeObject(c.getDia());
                //obj.writeObject(c.getMes());
                //obj.writeObject(c.getAno());
                //obj.writeObject(c.getSexo());
                obj.flush();
                obj.close();

                FileInputStream is =  new FileInputStream("D:\\System 32\\POO\\Lista 7\\Cadastro Clientes.txt");
                ObjectInputStream ois = new ObjectInputStream(is);
                Cliente c1 = (Cliente) ois.readObject();
                ois.close();
                System.out.println(c1.toString());
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }finally{
                sc.close();
            }

            /*try{
                FileInputStream is =  new FileInputStream("D:\\System 32\\POO\\Lista 7\\Cadastro Clientes.txt");
                ObjectInputStream ois = new ObjectInputStream(is);

                //LEITURA DO OBJETO CLIENTE NO ARQUIVO
                Object c1 = ois.readObject();


                //System.out.println(c1.toString());

                ois.close();

            }*/
    }

}
  • I just wanted to tell you what the problem is.

  • The error happens on this line: " Client C1 = (Client) ois.readObject();" Exception in thread "main" java.lang.Classcastexception: java.lang.String cannot be cast to lista7Questao2.Client I can’t understand why casting is not working.,

  • This Exception is saying that "ois.readObject();" returns a String, and not an object of the class "Cliente", is very simple. You can try using this String to create an Object Cliente, but it depends on the data that is in that String and the data needed to instantiate an object Cliente.

  • It worked, thank you :) !

No answers

Browser other questions tagged

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