Java InputStream Copy nio copyStream(InputStream input, OutputStream output)

Here you can find the source of copyStream(InputStream input, OutputStream output)

Description

Copia a stream output para a stream output, fechando as duas streans ao final do processo de copia.

License

Apache License

Parameter

Parameter Description
in stream de origem
out stream de destino

Declaration

public static void copyStream(InputStream input, OutputStream output)
        throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;

public class Main {
    /**/*from   w  w  w  .  j  a va 2  s .  c om*/
     * Copia a stream output para a stream output, fechando as duas streans ao final do processo de copia.
     * 
     * @param in stream de origem
     * @param out stream de destino
     */
    public static void copyStream(InputStream input, OutputStream output)
            throws IOException {
        // get an channel from the stream  
        final ReadableByteChannel inputChannel = Channels.newChannel(input);
        final WritableByteChannel outputChannel = Channels
                .newChannel(output);
        // copy the channels  
        fastChannelCopy(inputChannel, outputChannel);
        // closing the channels  
        inputChannel.close();
        outputChannel.close();
    }

    public static void fastChannelCopy(final ReadableByteChannel src,
            final WritableByteChannel dest) throws IOException {
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            // prepare the buffer to be drained
            buffer.flip();
            // write to the channel, may block
            dest.write(buffer);
            // If partial transfer, shift remainder down
            // If buffer is empty, same as doing clear()
            buffer.compact();
        }
        // EOF will leave buffer in fill state
        buffer.flip();
        // make sure the buffer is fully drained.
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
}

Related

  1. copy(InputStream stream, File file)
  2. copyStream(final InputStream aInStream, final OutputStream aOutStream)
  3. copyStream(final InputStream in)
  4. copyStream(final InputStream is, final OutputStream os)
  5. copyStream(InputStream in, OutputStream out)
  6. copyStream(InputStream src, OutputStream dest)