ObjectInputStream does not correctly display the object data

0

I want a program that reads a serialized file that contains the data of an object called "Comarca": on the one hand it has strings (comarq) and on the other ints (poblacio). The name of the file must be passed as a parameter (go, for the main args). The program mostly works fine, but it does not show me the data correctly.

The code is as follows:

public class LlegirFitxerObject {

public static FileInputStream fitxerALlegir = null;

public static void main(String[] args) {
    try {
        verificacioEntrada(args);
    } catch (ArrayIndexOutOfBoundsException e) {
        System.out.println(e.getMessage());
    } catch (IOException e) {
        System.out.println(e.getMessage());
    } catch (ClassNotFoundException e) {
        System.out.println("No se puede volver a leer el fichero.");
        System.out.println(e.getMessage());
    }
}

public static void verificacioEntrada(String[] args) throws ArrayIndexOutOfBoundsException, IOException, FileNotFoundException,
        ClassNotFoundException {

    if (args.length == 0) {
        throw new ArrayIndexOutOfBoundsException("ERROR");
    }

    if (args.length > 1) {
        throw new IOException("ERROR).");
    }

    fitxerALlegir = new FileInputStream(args[0]);

    ObjectInputStream input = new ObjectInputStream(fitxerALlegir);
    Object aux = input.readObject();

    while (aux != null) {
        if (aux instanceof Comarca) {
            System.out.println(aux);
        }
        aux = input.readObject();
    }
    input.close();

}

}

    
asked by MarcusF 27.09.2017 в 01:29
source

1 answer

1

When you use the method

System.out.println(Object objeto);

You make the equivalent of:

System.out.println(objeto.toString());

If your class has not implemented that method, overwriting the which implements Object , the only thing you'll see is the impression of:

getClass().getName() + '@' + Integer.toHexString(hashCode());

So your problem is solved by creating a String toString() {...} method in your Comarca class

    
answered by 27.09.2017 в 11:17