Народ, помогите разобраться - что делаю не так:
package com.javarush.task.task20.task2022;
import java.io.*;
/*
Переопределение сериализации в потоке
*/
public class Solution implements Serializable, AutoCloseable {
private transient FileOutputStream stream;
private String fileName;
public Solution(String fileName) throws FileNotFoundException {
this.fileName = fileName;
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 {
stream = new FileOutputStream(fileName, true);
in.defaultReadObject();
}
@Override
public void close() throws Exception {
System.out.println("Closing everything!");
stream.close();
}
public static void main(String[] args) throws Exception {
/*1) создать экземпляр класса Solution*/
Solution solution = new Solution("task2022.txt");
/*2) записать в него данные - writeObject*/
solution.writeObject("first string");
/*3) сериализовать класс Solution - writeObject(ObjectOutputStream out)*/
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("task2022.bin"));
oos.writeObject(solution);
oos.close();
/*4) десериализовать, получаем новый объект*/
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("task2022.bin"));
Object obj = ois.readObject(); /* !!! Здесь возникает NullPointerException !!! */
Solution newSolution = (Solution)obj;
ois.close();
/*5) записать в новый объект данные - writeObject*/
newSolution.writeObject("second string");
/*6) проверить, что в файле есть данные из п.2 и п.5*/
}
}