Java InputStream Copy nio copyStream(final InputStream in)

Here you can find the source of copyStream(final InputStream in)

Description

copy Stream

License

Apache License

Declaration

public static InputStream copyStream(final InputStream in)
            throws IOException 

Method Source Code

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

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
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 {
    public static InputStream copyStream(final InputStream in)
            throws IOException {
        final byte[] bs = streamToByteArray(in);
        return new ByteArrayInputStream(bs);
    }/*from w w  w  .  j  a  va 2  s  .co  m*/

    public static byte[] streamToByteArray(final InputStream in)
            throws IOException {
        final ByteArrayOutputStream result = new ByteArrayOutputStream();
        copy(in, result);
        result.close();
        return result.toByteArray();
    }

    private static void copy(final InputStream input,
            final OutputStream output) throws IOException {
        final ReadableByteChannel src = Channels.newChannel(input);
        final WritableByteChannel dest = Channels.newChannel(output);
        final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
        while (src.read(buffer) != -1) {
            buffer.flip();
            dest.write(buffer);
            buffer.compact();
        }
        buffer.flip();
        while (buffer.hasRemaining()) {
            dest.write(buffer);
        }
    }
}

Related

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