Почему при сериализации класса, получаю ошибку:
Exception in thread "main" java.io.IOException: Stream Closed
Ошибка исчезает, если удалить out.close()
и in.close()
. Почему нужно удалять?
public class Solution implements Serializable, AutoCloseable {
transient private FileOutputStream stream;
public Solution(String fileName) throws FileNotFoundException {
this.stream = new FileOutputStream(fileName);
}
public void writeObject(String string) throws IOException {
stream.write(string.getBytes());
stream.write("\n".getBytes());
stream.flush();
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();
out.close();
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
in.close();
}
@Override
public void close() throws Exception {
System.out.println("Closing everything!");
stream.close();
}
}
Вызов выглядит так:
Solution sol = new Solution("b:/data.txt");
FileOutputStream fileOutputStream = new FileOutputStream("b:/data.txt");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);
objectOutputStream.writeObject(sol);
FileInputStream fileInputStream = new FileInputStream("b:/data.txt");
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);
Solution new_sol = (Solution) objectInputStream.readObject();