JPedro JPedro - 10 days ago 6
Java Question

ObjectOutputStream ioexception on writeObject with ArrayList of objects

Thanks in advance for any reply.
Im trying to save an ArrayList of objects to file, but keep getting IOExeption.
The code :

public static final String FILE_PATH=""; // is set to blank for tests. It DOES create a file.

public static void saveToFileCl(ArrayList<cliente> al ) {
if (al != null ) {
try {
FileOutputStream file = new FileOutputStream(FILE_PATH+"cliente.dat");
ObjectOutputStream outStream = new ObjectOutputStream(file);
outStream.writeInt(cliente.getAuto_inc()); // works fine
outStream.writeObject(new Date()); // works fine - not needed just for testing!
outStream.writeObject(al); // exception !!!!
outStream.flush();
outStream.close();
} catch (IOException e) {System.out.println("Erro a gravar ficheiro de clientes!\n"+e.getCause());}
catch (Exception e) {System.out.println("Erro a desconhecido ao gravar ficheiro de clientes!\n"+e.getMessage());}
}
}


Does any one can tell me why the exception?

Answer

To write an instance into an OutputStream with OutputStream.writeObject(Object) you need the instance to be Serializable. This is that interface (java.io.Serializable) that tell that an instance can be store in a byte form.

You just need to add the interface to the class

class MyClass implements java.io.Serializable { ... }

There is no methods to implements, just this line is enough.