Save objects to Java file

Asked

Viewed 206 times

0

I have the following code:

package p10;
import java.io.*;
import java.util.*;
import myinputs.Ler;
public class P10 {

public static boolean verificawl (int i) throws ExcecaoWhile {
    if(i<0||i>7){
    throw new ExcecaoWhile("Dentro do intervalo >=0 e <=7");//lanca um nova excecao
    }
    return true;
}

public static void main(String[] args) throws IOException {
    int j;
    boolean n;
    ArrayList<Aluno> alunos = new ArrayList<Aluno>();
    while(true){
        do{
            System.out.println("[1]-Criar aluno");
            System.out.println("[2]-Consultar aluno, dado o seu número");
            System.out.println("[3]-Consultar aluno, dado o seu nome");
            System.out.println("[4]-Listar todos os alunos");
            System.out.println("[5]-Apagar um aluno");
            System.out.println("[6]-Corrigir o nome de um aluno");
            System.out.println("[7]-Guardar alunos");
            System.out.println("[0]-Sair");

            j = Ler.umInt();
            try{
                n=verificawl(j);//se correr bem nao lanca excecao
            }
            catch (ExcecaoWhile e) {
                System.out.println(e.getMessage());
                n=false;}
        }while(n!=true);

        switch (j) {
            case 1:

                Aluno a1;
                System.out.println("Introduza o nome:\n");    
                String s=Ler.umaString();
                a1 = new Aluno(s);
                alunos.add(a1);
                break;
            case 2:
                System.out.println("Introduza o numero");
                int k=Ler.umInt();
                try{
                    ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\\My_work\\ficheiroObjectStreams.dat"));
                    //ArrayList lista = (ArrayList) is.readObject();
                    /* */
                    int ult= is.readInt();
                    int c=0;
                    Aluno.setUltimo(ult);
                    ArrayList lista = (ArrayList) is.readObject();
                    for (int g = 0; g < lista.size(); g++){
                        //System.out.println((Aluno) lista.get(g));
                        String y= " ";
                        Aluno f = new Aluno(y);
                        f=(Aluno) lista.get(g);
                        if (k==f.getNumero()) {
                            System.out.println(f.getNome());
                            c++;
                        }     
                    }
                    if(c==0){
                            System.out.println("Nao existe registo");
                        }
                    is.close();
                }
                catch (IOException e){
                    System.out.println(e.getMessage());
                }
                catch (ClassNotFoundException e) {
                    System.out.println(e.getMessage());
                } 
                break;
            case 3:
                System.out.println("Introduza o nome");
                String h=Ler.umaString();
                try{
                    ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\\My_work\\ficheiroObjectStreams.dat"));
                    //ArrayList lista = (ArrayList) is.readObject();
                    /* */
                    int ult= is.readInt();
                    int c=0;
                    Aluno.setUltimo(ult);
                    ArrayList lista = (ArrayList) is.readObject();
                    for (int g = 0; g < lista.size(); g++){
                        //System.out.println((Aluno) lista.get(g));
                        String y= " ";
                        Aluno f = new Aluno(y);
                        f=(Aluno) lista.get(g);
                        if (h.equals(f.getNome())) {
                            System.out.println(f.getNumero());
                            c++;
                        }     
                    }
                    if(c==0){
                            System.out.println("Nao existe registo");
                        }
                    is.close();
                }
                catch (IOException e){
                    System.out.println(e.getMessage());
                }
                catch (ClassNotFoundException e) {
                    System.out.println(e.getMessage());
                }
                break;
            case 4:

               List<Aluno> vem = new ArrayList<Aluno>();
               vem=LerObjecto.Ler_obj();
                for (int i = 0; i < vem.size(); i++) {
                    System.out.println(vem.get(i));
                }
                break;
            case 5:
                System.out.println("Introduza o nome");
                String p=Ler.umaString();
                try{
                    ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\\My_work\\ficheiroObjectStreams.dat"));
                    //ArrayList lista = (ArrayList) is.readObject();
                    /* */
                    int ult= is.readInt();
                    int c=0;
                    Aluno.setUltimo(ult);
                    ArrayList lista = (ArrayList) is.readObject();
                    for (int g = 0; g < lista.size(); g++){
                        //System.out.println((Aluno) lista.get(g));
                        String y= " ";
                        Aluno f = new Aluno(y);
                        f=(Aluno) lista.get(g);
                        if (p.equals(f.getNome())) {
                            lista.remove(f);

                            try {
                                ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream ("d:\\My_work\\ficheiroObjectStreams.dat"));
                                //os.writeObject(alunos);
                                /* */
                                os.writeInt(Aluno.getUltimo());
                                os.writeObject(lista);
                                os.flush();
                                os.close();
                            }
                            catch (IOException e){
                                System.out.println(e.getMessage());
                            }
                            c++;
                        }     
                    }
                    if(c==0){
                            System.out.println("Nao existe registo");
                        }



                }
                catch (IOException e){
                    System.out.println(e.getMessage());
                }
                catch (ClassNotFoundException e) {
                    System.out.println(e.getMessage());
                }
                break;
            case 6:
                break;
            case 7:
                try {
                    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream ("d:\\My_work\\ficheiroObjectStreams.dat",true));
                    //os.writeObject(alunos);
                    /* */
                    os.writeInt(Aluno.getUltimo());
                    os.writeObject(alunos);
                    os.flush();
                    os.close();
                }
                catch (IOException e){
                    System.out.println(e.getMessage());
                }
                break;
        }
        if (j==0) {
            break;
        }
    }//while true
}
}

When I select case 4 it shows the names then I "quit" when I run(run) and press 4 it shows in the same the previous names but if create a new one and press 7 when ask to list the names (option 4), this now created does not appear

public class LerObjecto {

public static List<Aluno> Ler_obj() {
    List<Aluno> lista = new ArrayList<Aluno>();
    try{
        ObjectInputStream is = new ObjectInputStream(new FileInputStream("d:\\My_work\\ficheiroObjectStreams.dat"));
        //ArrayList lista = (ArrayList) is.readObject();
        /* */
        int ult= is.readInt();
        Aluno.setUltimo(ult);
        while(true){
            lista.add((Aluno) is.readObject()); //le outro objeto e adicionar à lista
        }


    }
    catch (IOException e){
        System.out.println(e.getMessage());
    }
    catch (ClassNotFoundException e) {
        System.out.println(e.getMessage());
    }
    return lista;
}

}
  • Possible duplicate of Save.txt file

  • I already answered one similar question in relation to reading/saving objects in file. However the correct way to structure is to read everything at the beginning of the program to an Arraylist and write everything at the end of the program, minimizing the written file, which in itself solves the problem has at the moment

  • yes he writes but when I ask to list again this servant does not appear to me and I do not understand why

  • now when I call the function it returns this error Exception in thread "main" java.lang.Classcastexception: java.util.Arraylist cannot be cast to P10.Student

1 answer

0

I think the problem happens when you save the new Student, instead of saving the new List you are making append with the previous List.

            case 7:
            try {
                ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream ("d:\\My_work\\ficheiroObjectStreams.dat",true));
                ...
            }
            catch (IOException e){
                System.out.println(e.getMessage());
            }
            break;

You have to change this line (where it has true, set false):

Objectoutputstream os = new Objectoutputstream(new Fileoutputstream ("d: my_work fileObjectStreams.dat",false));

Browser other questions tagged

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