title: Why DataoutputStream and BufferedWriter creation order is important?
body: <p>I'm trying to create a simple client where at first I comunicate to a server:</p>
  
  <ol>
  <li>A filename</li>
  <li>The sequence of chunks which compose the file</li>
  </ol>
  
  <p>So for the first one I thought to use to a BufferedWriter: this choice was made since I can't use on the server a InputStreamReader from the moment that the readLine() method is deprecated. However, for the second one I used a OutputStreamWriter since it is the better (only?) one choice to write a byte array on a socket.</p>
  
  <p>So, this is the first version of my client code:</p>
  
  <pre><code>public class Client
  {
      private static final int PART_SIZE = 1000000; // 1MB
  
      public static void main(String[] args) throws IOException
      {
          final Path file = Paths.get(args[0]);
          final String filenameBase = file.getFileName().toString();
          final byte[] buf = new byte[PART_SIZE];    
          Socket socket = new Socket(InetAddress.getLocalHost(),8080);
          System.out.println("Socket created");
          int partNumber = 0;
          Path part;
          int bytesRead;
          byte[] toWrite;
  
          try (
              final InputStream in = Files.newInputStream(file);
              final BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
              final DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
          ) {
              System.out.println("closed="+socket.isClosed());
              bw.write(filenameBase,0,filenameBase.length());
              //other stuff for the chunk creation and spedition
          }
      }
  }
  </code></pre>
  
  <p>However, if I run this code, this exception occours:</p>
  
  <pre><code>Exception in thread "main" java.net.SocketException: Socket closed
      at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:121)
      at java.net.SocketOutputStream.write(SocketOutputStream.java:159)
      at sun.nio.cs.StreamEncoder.writeBytes(StreamEncoder.java:221)
      at sun.nio.cs.StreamEncoder.implClose(StreamEncoder.java:316)
      at sun.nio.cs.StreamEncoder.close(StreamEncoder.java:149)
      at java.io.OutputStreamWriter.close(OutputStreamWriter.java:233)
      at java.io.BufferedWriter.close(BufferedWriter.java:266)
      at PAD.Charlie.Client.App.main(App.java:50)
  </code></pre>
  
  <p>The strange thing is that <strong>if I change the order between the <code>BufferedWriter</code> and the <code>DataOutputStream</code> inside the <code>try</code> everthing works fine!</strong></p>
  
  <p>Actually the idea has come because I remembered something about it from the java course, but I can't really remember the details! Can you help me about this doubt that I have? Thanks a lot! :)</p>