-1

Tenho o seguinte código:

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
}
}

Quando eu seleciono caso 4 ele mostra os nomes depois faço "sair" quando volto a executar(run) e pressiono 4 ele mostra na mesma os nomes anteriores mas se criar um novo e pressionar 7 quando pedir para listar os nomes (opção 4), este agora criado não aparece

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;
}

}
4
  • Possível duplicata de Gravar arquivo.txt
    – NoobSaibot
    5/12/2017 às 23:59
  • Já respondi a uma pergunta parecida em relação a ler/guardar objetos em ficheiro. No entanto a forma correta de estruturar é ler tudo no inicio do programa para um ArrayList e escrever tudo no fim do programa, minimizando as escritas em ficheiro, que só por si resolve o problema tem no momento
    – Isac
    6/12/2017 às 0:16
  • sim ele escreve mas quando peço para listar de novo esse criado não me aparece e não percebo porque 6/12/2017 às 0:18
  • agora quando chamo a função ele devolve este erro Exception in thread "main" java.lang.ClassCastException: java.util.ArrayList cannot be cast to p10.Aluno 6/12/2017 às 0:54

1 Resposta 1

0

Acho que o problema acontece quando guardas o novo Aluno, ao invés de salvares a nova Lista estas a fazer append com a Lista anterior.

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

Tens de alterar esta linha (onde tem true, coloca false):

ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream ("d:\My_work\ficheiroObjectStreams.dat",false));

Você deve fazer log-in para responder a esta pergunta.

Esta não é a resposta que você está procurando? Pesquise outras perguntas com a tag .