package net.yeputons.spbau.spring2016.torrent;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.NoSuchFileException;
import java.nio.file.Path;

public class StateFileHolder<T extends Serializable> implements StateHolder<T> {
    private static final Logger LOG = LoggerFactory.getLogger(StateFileHolder.class);
    private final Path storage;
    private final T state;

    @SuppressWarnings("unchecked")
    public StateFileHolder(Path storage, T defaultValue) {
        T state = defaultValue;
        this.storage = storage;
        LOG.debug("Loading state of type {} from {}", defaultValue.getClass().getCanonicalName(), storage);
        try (ObjectInputStream in = new ObjectInputStream(Files.newInputStream(storage))) {
            state = (T) in.readObject();
        } catch (NoSuchFileException | FileNotFoundException ignored) {
            LOG.debug("File not found, backing to default");
        } catch (IOException | ClassNotFoundException e) {
            LOG.warn("Unable to load state from file, backing to default", e);
        }
        this.state = state;
    }

    @Override
    public T getState() {
        return state;
    }

    @Override
    public void save() throws IOException {
        synchronized (state) {
            try (ObjectOutputStream out = new ObjectOutputStream(Files.newOutputStream(storage))) {
                out.writeObject(state);
            }
        }
    }
}

@@ -721,22 +721,16 @@
    try (
-Object
 InputStr
@@ -737,16 +737,57 @@
 eam 
+f
 in = 
-new
+Files.newInputStream(storage);%0A            
  Obj
@@ -800,26 +800,32 @@
 utStream
-(Files.new
+ in = new Object
 InputStr
@@ -824,32 +824,27 @@
 InputStream(
-storage)
+fin
 )) %7B%0A       
@@ -1368,22 +1368,16 @@
    try (
-Object
 OutputSt
@@ -1385,17 +1385,63 @@
 eam 
+f
 out = 
-new
+Files.newOutputStream(storage);%0A                
  Obj
@@ -1459,18 +1459,25 @@
 ream
-(Files.new
+ out = new Object
 Outp
@@ -1485,24 +1485,20 @@
 tStream(
-storage)
+fout
 )) %7B%0A   

use try-with-resources better with chained streams