简体   繁体   中英

Trying to read a serialized file

I've been trying to read this file and add each object in an ArrayList . The problem is that it never goes inside the while loop.

Do you guys know what could be the problem? And may I improve the syntax of the code?

public ArrayList<Notificacion> obtenerListaNovedades() {
    ObjectInputStream ois = null;
    try {
        if (f.exists()) {
            FileInputStream fis = new FileInputStream(f);
            ois = new ObjectInputStream(fis);
            while (true) {
                Notificacion notificacion = (Notificacion) ois.readObject();                    
                listaNotificaciones.add(notificacion);        
            }
        } else {
            System.out.println("hay algo ene l archi");
        }           
    } catch (Exception e) {

    }
    return listaNotificaciones;
}

That while loop will only exit when an exception occurs as well. It would be better to control the loop with a boolean, then catch the EOFException to exit the loop by setting the boolean to false. Something like:

boolean hasObjects = true;

while (hasObjects) {
    String notificacion = null;
    if (ois != null) {
        try {
            notificacion = (Notificacion) ois.readObject();
            listaNotificaciones.add(notificacion);
        } catch (EOFException e) {
            hasObjects = false;
        } catch (ClassNotFoundException | IOException e) {
            e.printStackTrace();
        }
    } else {
        hasObjects = false;
    }
}

never just swallow up exceptions, otherwise you will not know what is going wrong

change to

catch (Exception e) {
   e.printStackTrace ();
}

Your most likely getting an exception when attempting to read the file and because your not doing anything with the exception, you don't know what is going on. At the very least, print the contents of the exception to the console and have a look:

e.printStackTrace();
e.getMessage();

So, again, have a look at the exception and go from there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM