Java Convert via ByteBuffer toByteArray(InputStream input, boolean nioCopy)

Here you can find the source of toByteArray(InputStream input, boolean nioCopy)

Description

to Byte Array

License

Apache License

Declaration

public static final byte[] toByteArray(InputStream input, boolean nioCopy) throws IOException 

Method Source Code


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

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 {
    private static final int DEFAULT_BUFFER_SIZE = 8192;

    public static final byte[] toByteArray(InputStream input, boolean nioCopy) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        if (nioCopy)
            nioCopy(input, baos);/*from   w ww .j  a v  a 2  s  .co  m*/
        else
            copy(input, baos);

        return baos.toByteArray();
    }

    public static final void nioCopy(InputStream input, OutputStream output) throws IOException {
        nioCopy(Channels.newChannel(input), Channels.newChannel(output));
    }

    public static final void nioCopy(ReadableByteChannel input, WritableByteChannel output) throws IOException {
        try {
            ByteBuffer buffer = ByteBuffer.allocate(DEFAULT_BUFFER_SIZE);
            while (input.read(buffer) != -1) {
                //Flip buffer
                buffer.flip();
                //Write to destination
                output.write(buffer);
                //Compact
                buffer.compact();
            }

            //In case we have remainder
            buffer.flip();
            while (buffer.hasRemaining()) {
                //Write to output
                output.write(buffer);
            }
        } finally {
            if (input != null) {
                input.close();
                input = null;
            }

            if (output != null) {
                output.close();
                output = null;
            }
        }
    }

    public static final int copy(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int totalBytesRead = 0;
        int bytesRead = 0;

        while (-1 != (bytesRead = input.read(buffer))) {
            output.write(buffer, 0, bytesRead);
            totalBytesRead += bytesRead;
        }

        return totalBytesRead;
    }
}

Related

  1. toByteArray(BitSet bits)
  2. toByteArray(char[] chars)
  3. toByteArray(double value)
  4. toByteArray(double[] doubleArray)
  5. toByteArray(float[] floatArray)
  6. toByteArray(int i)
  7. toByteArray(int integer)
  8. toByteArray(int value)
  9. toByteArray(int value)