My problem is with ObjectOutputStream
, it only works when I write an object the first time. If I add another object to that file, it sends me the following Exception:
java.io.StreamCorruptedException: invalid type code: AC
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1596)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:428)
at Ejemplo.leer(Ejemplo.java:62)
at Ejemplo.main(Ejemplo.java:17)
Next I show you the code of how I am saving and recovering the objects:
public static void main(String[] args) {
Alumno alu = new Alumno("29521268D", "Pepe García");
Alumno alu2 = new Alumno("23456789L", "Jose Ramón");
escribir(alu, "alumnos_prueba.dat");
//escribir(alu2, "alumnos_prueba.dat");
leer("alumnos_prueba.dat");
}
public static <T> void escribir(T objeto,String nombre_archivo){
FileOutputStream fos = null;
ObjectOutputStream oos = null;
try {
fos = new FileOutputStream(nombre_archivo,true);
oos = new ObjectOutputStream(fos);
oos.writeObject(objeto);
oos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (oos!=null) {
try {
oos.close();
fos.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
@SuppressWarnings("unchecked")
public static <T> void leer(String nombre_archivo) {
FileInputStream fis = null;
ObjectInputStream ois = null;
try {
fis = new FileInputStream(nombre_archivo);
ois = new ObjectInputStream(fis);
T objeto;
while(fis.available()>0) {
objeto = (T)ois.readObject();
System.out.println(objeto);
}
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}}
The Student class has implemented the serializable interface and put a serialVersionUID
public class Alumno implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String dni;
private String nombre;
public Alumno(String dni, String nombre) {
this.setNombre(nombre);
this.setDni(dni);
}
public String getDni() {
return dni;
}
public void setDni(String dni) {
this.dni = dni;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
@Override
public String toString() {
// TODO Auto-generated method stub
return "DNI: "+this.getDni()+" Nombre: "+this.getNombre();
}}