-2

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?

9
  • 2
    please add the complete stacktrace Commented Nov 29, 2016 at 12:09
  • Full error stack trace please Commented Nov 29, 2016 at 12:11
  • Is cliente serializable ? Something tell me the stacktrace tell you exactly the same think... Commented Nov 29, 2016 at 12:12
  • No, it is not serializable. Mainely because i dint know it has to be. What is it and where do i get more info about that? Commented Nov 29, 2016 at 12:20
  • 1
    Possible duplicate of Getting NotSerializableException when trying to write object Commented Nov 29, 2016 at 12:26

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.