JPedro JPedro - 1 year ago 92
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 !!!!
} 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 Source

To write an instance into an OutputStream with OutputStream.writeObject(Object) you need the instance to be Serializable. This is that interface ( 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 { ... }

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download