预先感谢您的回复。 我试图将对象的ArrayList保存到文件,但不断获得IOExeption。 代码:
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());}
}
}
有没有人可以告诉我为什么会有例外?
答案 0 :(得分:0)
要将实例写入带有OutputStream.writeObject(Object)
的OutputStream,您需要实例为Serializable
。这是一个接口(java.io.Serializable),它告诉实例可以以字节形式存储。
您只需要将接口添加到类
class MyClass implements java.io.Serializable { ... }
没有方法可以实现,只需这一行即可。