https://pastein.ru/t/ze

  скопируйте уникальную ссылку для отправки


public class Solution implements Serializable, AutoCloseable {                                                  
    private transient 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();                                                  
                                                  
    }                                                  
                                                  
    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {                                                  
        in.defaultReadObject(); 
        stream = new FileOutputStream("testik2.txt",true);
                                                          
    }                                                  
                                                  
    @Override                                                  
    public void close() throws Exception {                                                  
        System.out.println("Closing everything!");                                                  
        stream.close();                                                  
    }