#EXCEPTION STREAMCORRUPTED

65 messages · Page 1 of 1 (latest)

hollow jungle
#

Hi so my code is this

public static void main(String[] args) throws IOException, ClassNotFoundException {

        char opc;
        do {
            System.out.println("1- Agregar contactos\n2- Modificar contacto\n3- Mostrar\n4- Salir");
            opc = in.nextLine().charAt(0);

            switch (opc) {
            case '1':
                agregarContacto();
                break;

            case '2':
                modificarContacto();
                break;

            case '3':
                mostrarContactos();
            }

        } while (opc != '4');
    }

    public static void agregarContacto() throws IOException {
        FileOutputStream fos = new FileOutputStream(fichero, true);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        for (int i = 0; i < 4; i++) {
            System.out.println("Introduce " + textoParaMostrar[i]);
            textoAGuardar[i] = in.nextLine();
        }

        Persona nuevoContacto = new Persona(textoAGuardar[0], textoAGuardar[1], textoAGuardar[2], textoAGuardar[3]);

        oos.writeObject(nuevoContacto);
        oos.flush();
    }
    public static void mostrarContactos() throws IOException, ClassNotFoundException {
        
        if (fichero.exists()) {
                FileInputStream fis = new FileInputStream(fichero);
                ObjectInputStream ois = new ObjectInputStream(fis);
                while (true) {
                    try {
                        Persona p = (Persona) ois.readObject();
                        System.out.println(p.toString());
                    } catch (EOFException e) {
                        break;
                    }
                }

                ois.close(); // Cierra el ObjectInputStream después de leer todos los contactos
        } else {
            System.out.println("El archivo no existe o no hay contactos almacenados.");
        }
    }
foggy sluiceBOT
#

This post has been reserved for your question.

Hey @hollow jungle! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

hollow jungle
#

So the thing im doing is, Im creating an object of type Person everytime I mark 1 and that object saves in a file serelizated because I have another Class which is called Person and there I implemented the Serializable, so the THING is when I want to read all the objetcs, which means deserenize them it comes an exception into my screem.
I dont get why if Im doing corrently as far as I know by my self.

Any help is welcome, Thanks!!!!!!!

foggy sluiceBOT
random brook
#

could you share the stacktrace

hollow jungle
#

do u want me to send u both classes?

random brook
#

the error. Please send the full error

hollow jungle
#

ohhh

#

yes

#

java.io.StreamCorruptedException: invalid type code: AC
at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1764)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:509)
at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:467)
at clase/agendaobjetos.Main.mostrarContactos(Main.java:83)
at clase/agendaobjetos.Main.main(Main.java:40)
1- Agregar contactos

#

@random brook

#

**java.io.StreamCorruptedException: invalid type code: AC
at **

random brook
#

how many ObjectOutputStreams do you create ?

hollow jungle
#

I created one

#

Inside the method to create a person:
1 FileOutputStream
1 ObjectOutputStream

Inside the method to show all the persons:
1 FileInputStream
1 ObjectInputStream

random brook
#

I see. You can't use the append option with an ObjectOutputStream. It will write its header to the file again causing the ObjectInputStream to throw said error.

#

I'd also recommend creating a simple CSV file instead of using ObjectOutputStream if you are just looking for a way to store the information of a Person in a file.

hollow jungle
random brook
#

FileOutputStream fos = new FileOutputStream(fichero, true); You are creating a FileOutputStream with the append option set. This won't work in combination with a ObjectOutputStream remove the boolean in the constructor.

hollow jungle
#

It does not show all the objects I created as person

random brook
#

are you reading the person from a file every time you are querying them ?

hollow jungle
#

No, I want to read all the persons whenever I use the method mostrar()

#

not everytime I create one person I show it, thats not what I want

random brook
#

are you not allowed to hold the created objects in memory using an ArrayList ?

hollow jungle
#

yes I am

random brook
#

then use an arraylist and once the program terminates, write all person objects to the file. On program start up read from said file to load the saved Person objects

hollow jungle
random brook
#

no. You don't write anything to the file while the program is running. When the user inputs 4 (he wants to terminate the program) then you write all objects stored in the arraylist to a file with an ObjectOutputStream. When you start the program the first thing you do is load all objects from the file using an ObjectInputStream

hollow jungle
random brook
#

exactly. and when you press 3 you don't read the objects from a file but straight from the arraylist

hollow jungle
random brook
#
#Program start
read Person objects from File, store them in an ArrayList:
normal Program execution
write all Person objects from the ArrayList to the file
#Program end
random brook
hollow jungle
# random brook you'll read from the file when you start the program

okay so here I modified this as

public static void agregarContacto() throws IOException {
        
        FileOutputStream fos = new FileOutputStream(fichero);
        ObjectOutputStream oos = new ObjectOutputStream(fos);

        for (int i = 0; i < 4; i++) {
            System.out.println("Introduce " + textoParaMostrar[i]);
            textoAGuardar[i] = in.nextLine();
        }

        // Crea un nuevo objeto Persona con los datos proporcionados
        Persona nuevoContacto = new Persona(textoAGuardar[0], textoAGuardar[1], textoAGuardar[2], textoAGuardar[3]);
        contactos.add(nuevoContacto);

}

that method add every person into the arraylist

#

with the implicit method .add of the arraylist

#

so we put the case I add 3 persons, ifw

random brook
#

alright lastly get rid of these two lines:

        FileOutputStream fos = new FileOutputStream(fichero);
        ObjectOutputStream oos = new ObjectOutputStream(fos);
hollow jungle
#

okayokay

hollow jungle
#

theyre inside my arraylist

#

but Im obligated to use the method ois.readObject()

random brook
#

you loop over the list (either a traditional for loop or a for-each loop) and print each person object

random brook
hollow jungle
#

but thats not what I want

#

what I want is to Serializate into a file and then show it

random brook
#

You should create two methods:

public static ArrayList<Person> loadObjects() {
  //...
}

public static void saveObjects(ArrayList<Person> list) {
  //...
}

and they should be called like so:

public static void main(String[] args) {
    ArrayList<Person> persons =  loadObjects();
    do {  
        //...
    }while(opc != 4);
    saveObjects(persons);
}
hollow jungle
#

but there im not using the ObjectOutputStream guardarContactos = new ObjectOutputStream(new FileOutputStream(archivo))

#

and I need to use it

#

thats the examples it shows

random brook
#

the code for writing to the file should be in saveObjects() and the code for reading from the file should be in loadObjects()

hollow jungle
random brook
#

let's say you saved two Person objects in the file. When start the program you want both of these objects to be displayed if you print all known Person objects. If that first method doesn't return anything you can't display both objects.

hollow jungle
#

I did it

foggy sluiceBOT
# foggy sluice

Before your post will be closed, would you like to express your gratitude to any of the people who helped you? When you're done, click I'm done here. Close this post!.

hollow jungle
#

@random brook ty

#

anyways!