Reputation: 58
I'm trying to serialize an instance from a class using inheritance.
And this is the class where I try to serialize the data
public class Serializacion {
static int agregarProfeTitular(ProfesorTitular p){
int status = 0;
try {
FileOutputStream fos = new FileOutputStream("profestitulares.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
ArrayList pi = conseguirTodosProfesTitulares();
pi.add(p);
oos.writeObject(pi);
oos.close();
fos.close();
status = 1;
} catch (IOException e) {
System.out.println("Error al agregar el prof titular..."+Arrays.toString(e.getStackTrace()));
}
return status;
}
static ArrayList<ProfesorTitular> conseguirTodosProfesTitulares(){
ArrayList<ProfesorTitular> pi = new ArrayList<ProfesorTitular>();
try {
FileInputStream fis = new FileInputStream("profestitulares.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
pi = (ArrayList<ProfesorTitular>) ois.readObject();
ois.close();
fis.close();
} catch (Exception e) {
System.out.println("Error al conseguir a los profes titulares..."+e);
}
return pi;
}
}
At the end the try-catch throws me
java.io.EOFException
at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2950)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1534)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:427)
at profesores.Serializacion.conseguirTodosProfesTitulares(Serializacion.java:69)
at profesores.Serializacion.agregarProfeTitular(Serializacion.java:46)
The idea is that when I want to write some data in my file first I get the data that already exists parsing it as an arraylist and then i return that arraylist and i just add the new data. It works writing the file, but reading it doesnt work.
EDIT:
This is the class code that I try to serialize:
public class ProfesorTitular extends Profesor {
int horasBase;
public ProfesorTitular(int id, String nombre, String clase, int horasBase) {
super(id, nombre, clase);
this.horasBase = horasBase;
}
public int getHorasBase() {
return horasBase;
}
public void setHorasBase(int horasBase) {
this.horasBase = horasBase;
}
}
Upvotes: 0
Views: 492
Reputation: 310907
FileOutputStream
for the very poorly named file profestitulares.txt
. Serialized data is not text and should not be saved in files with the .txt extension.ObjectOutputStream
around this stream, which writes the object stream header.FileInputStream
for the same file, which is now empty apart from the object stream header, whatever its state may have previously been.ObjectInputStream
around this, which fails, because there is a stream header but no objects in this logically empty file.Solution: read the objects from the file before you create the new one.
Upvotes: 1