Problem with ClassCastException

1

I'm having a problem with reading / writing objects in java using ObjectInputStream. The case is the following, I want to store in a file a series of objects of different type (different classes that inherit from it). But the point is that I want to first create the file and add some objects, and then using another method keep writing about the same file.

So I created the following main that tries to do this, but I do not know why the java.lang.ClassCastException exception jumps on line 24, apparently it's a problem with the cast of those objects that I have added with the method "secondWrite ()" to the file, but for more laps that I give I do not take out the solution.

In short, the main main of the program would be the following.

public class Main2 {
public static void main(String args[]) {
    PrimeraEscritura();
    SegundaEscritura();
    //Lectura
    try(ObjectInputStream fe=new ObjectInputStream(new FileInputStream("c:\prueba\hola.dat"))){
        Revistas revistaLeida=null;
        Libros libroLeido=null;

        Object lector=fe.readObject();

        while(lector!=null) {
            if (lector instanceof Libros) {
                libroLeido= (Libros) lector;
                System.out.println(libroLeido.toString());
            }else {
                revistaLeida= (Revistas) lector;
                System.out.println(revistaLeida.toString());
            }
            lector=fe.readObject();
        };

        System.out.println("Lectura finalizada");

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }catch (ClassNotFoundException e) {
        e.printStackTrace();}
}

public static void PrimeraEscritura() {
        //Primera escritura

        Libros libro=new Libros("B","BB",new GregorianCalendar(1999,3,12),"A","A");
        Libros libro2=new Libros("B","BB",new GregorianCalendar(1999,3,12),"B","B");
        Revistas revista=new Revistas("A","AA",new GregorianCalendar(1999,3,12),1,22);
        try(ObjectOutputStream fs = new ObjectOutputStream(new FileOutputStream("c:\prueba\hola.dat"))) {

            fs.writeObject((Object) libro);
            fs.writeObject((Object) libro2);
            fs.writeObject((Object) revista);
        fs.close();
        }catch (FileNotFoundException ef) {
            System.out.println("ERROR: ARCHIVO NO ENCONTRADO");
            ef.printStackTrace();
        }catch (IOException e) {
            System.out.println("ERROR DE ESCRITURA");
            e.printStackTrace();
        }
}


public static void SegundaEscritura() {
        //Segunda escritura
        Revistas revista2=new Revistas("A","AA",new GregorianCalendar(1999,3,12),2,22);

        try(MiObjectOutputStream mifs = new MiObjectOutputStream(new FileOutputStream("c:\prueba\hola.dat",true))) {
            mifs.writeObject((Object) revista2);
            mifs.close();           
        }catch (FileNotFoundException ef) {
            System.out.println("ERROR: ARCHIVO NO ENCONTRADO");
            ef.printStackTrace();
        }catch (IOException e) {
            System.out.println("ERROR DE ESCRITURA");
            e.printStackTrace();
        }
}

The output stream MiObjectOutputStream that I am using for the second script is a modified class so that it does not add the header to the file again, this would be the class

public class MiObjectOutputStream extends ObjectOutputStream {

/** Constructor que recibe OutputStream */
public MiObjectOutputStream(OutputStream out) throws IOException{
    super(out);
}

/** Constructor sin parámetros */
protected MiObjectOutputStream() throws IOException, SecurityException{
    super();
}

/** Redefinición del método de escribir la cabecera para que no haga nada. */
protected void writeStreamHeader() throws IOException{
}

I also add the trace of the exception

Exception in thread "main" java.lang.ClassCastException: java.io.ObjectStreamClass cannot be cast to java.lang.String
at java.io.ObjectInputStream.readTypeString(Unknown Source)
at java.io.ObjectStreamClass.readNonProxy(Unknown Source)
at java.io.ObjectInputStream.readClassDescriptor(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readNonProxyDesc(Unknown Source)
at java.io.ObjectInputStream.readClassDesc(Unknown Source)
at java.io.ObjectInputStream.readOrdinaryObject(Unknown Source)
at java.io.ObjectInputStream.readObject0(Unknown Source)
at java.io.ObjectInputStream.readObject(Unknown Source)
at EjercicioObject.Main2.main(Main2.java:24)

Thank you very much

    
asked by Antonio Agustin 12.04.2018 в 23:50
source

1 answer

0

According to an answer in the version in English of the site :

Instead of doing nothing in writeStreamHeader() , invoke reset() :

/**
 * Redefinición del método de escribir la cabecera para que no haga
 * nada.
 */
@Override
protected void writeStreamHeader() throws IOException {
    reset();
}

In addition, when reading objects from the stream you must take into account that reaching the end of the file is not an error:

while (lector != null) {
    if (lector instanceof Libros) {
        libroLeido = (Libros) lector;
        System.out.println(libroLeido.toString());
    } else {
        revistaLeida = (Revistas) lector;
        System.out.println(revistaLeida.toString());
    }
    try {
        lector = fe.readObject();
    } catch (EOFException eof) {
        lector = null;
    }
}
    
answered by 13.04.2018 / 17:24
source