title: How to use NIO to write InputStream to File?
body: <p>I am using following way to write <code>InputStream</code> to <code>File</code>:</p>
  <pre><code>private void writeToFile(InputStream stream) throws IOException {
      String filePath = &quot;C:\\Test.jpg&quot;;
      FileChannel outChannel = new FileOutputStream(filePath).getChannel();       
      ReadableByteChannel inChannel = Channels.newChannel(stream);
      ByteBuffer buffer = ByteBuffer.allocate(1024);
      
      while(true) {
          if(inChannel.read(buffer) == -1) {
              break;
          }
          
          buffer.flip();
          outChannel.write(buffer);
          buffer.clear();
      }
      
      inChannel.close();
      outChannel.close();
  }
  </code></pre>
  <p>I was wondering if this is the right way to use NIO. I have read a method <a href="http://docs.oracle.com/javase/1.5.0/docs/api/java/nio/channels/FileChannel.html#transferFrom%28java.nio.channels.ReadableByteChannel,%20long,%20long%29" rel="noreferrer"><code>FileChannel.transferFrom</code></a>, which takes three parameter:</p>
  <ol>
  <li>ReadableByteChannel src</li>
  <li>long position</li>
  <li>long count</li>
  </ol>
  <p>In my case I only have <code>src</code>, I don't have the <code>position</code> and <code>count</code>, is there any way I can use this method to create the file?</p>
  <p>Also for Image is there any better way to create image only from <code>InputStream</code> and NIO?</p>
  <p>Any information would be very useful to me. There are similar questions here, in SO, but I cannot find any particular solution which suites my case.</p>