Error: java.io.StreamCorruptedException: invalid type code: AC

3

Can anyone give me a hand with that?

The idea is to recover all the "Video" objects, which are saved in a file, but apparently I'm only recovering the first object and then I get this error: java.io.StreamCorruptedException: invalid type code: AC.

I leave a part of the method that, in theory, should recover said objcts from the file:

Thank you very much already.

public static void recuperarVideo(Video unVideo) {
    try {ObjectInputStream ois = new ObjectInputStream(new 

FileInputStream("F:/JAVA Projectos/taller01/Datos/Videos.txt"));
       Object aux = ois.readObject();
        // Mientras haya objetos
        while (aux!=null)
        {if (aux instanceof Video)
            System.out.println(aux);  // Se escribe en pantalla el objeto
            aux = ois.readObject();
        }   ois.close();}       
catch (Exception e) {
        e.printStackTrace();}}

Method that saves the "video" object:

 public static void guardarVideo(Video unVideo) {

    try {ObjectOutputStream escribiendoFichero = new ObjectOutputStream(new 
FileOutputStream("F:/JAVA Projectos/taller01/Datos/Videos.txt",true));


        escribiendoFichero.writeObject(unVideo);
        escribiendoFichero.close(); }
     catch (EOFException e) {  return;}
     catch (Exception e) {
        e.printStackTrace();    }           }
    
asked by Rodro 28.07.2018 в 02:13
source

1 answer

2

StreamCorruptedException is thrown when more than once a ObjectInputStream or ObjectOutputStream is used.

Remitiendome to your code:

  //...
  Object aux = ois.readObject();
  // Mientras haya objetos
  while (aux!=null) {
    if (aux instanceof Video)
      System.out.println(aux);  // Se escribe en pantalla el objeto
      aux = ois.readObject();
  }
  //...

The line that sends the exception is aux = ois.readObject(); a second call occurs to ObjectInputStream there.

To somehow take that list of objects you could write something like:

videos = (ArrayList <Video>) OIS.readObject();

if(videos != null) {
  for( Video V : videos ) {
    System.out.println(V);
  }
}

I hope you help.

PD. As a backup I leave this article quite useful about Read and Write Java Objects in Files

Edit: As it is a question of using a list, to the method guardarVideo() it is necessary to correct the way in which it saves the data. The idea is, better, to serialize a single collection of objects instead of serializing / deserializing multiple objects one by one.

    
answered by 28.07.2018 в 05:03