Java File Read via ByteBuffer readFully(InputStream in)

Here you can find the source of readFully(InputStream in)

Description

Reads until the end of the input stream, and returns the contents as a byte[]

License

Apache License

Declaration

public static byte[] readFully(InputStream in) throws IOException 

Method Source Code

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

import java.io.IOException;
import java.io.InputStream;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static final int BUFFER_SIZE = 8192;

    /**//from ww  w.j a  v a2 s. c  om
     * Reads until the end of the input stream, and returns the contents as a byte[]
     */
    public static byte[] readFully(InputStream in) throws IOException {
        List<ByteBuffer> buffers = new ArrayList<ByteBuffer>(4);
        while (true) {
            ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE);
            int count = in.read(buffer.array(), 0, BUFFER_SIZE);
            if (count > 0) {
                buffer.limit(count);
                buffers.add(buffer);
            }
            if (count < BUFFER_SIZE)
                break;
        }

        return getAsBytes(buffers);
    }

    /**
     * Copies the contents of the buffers into a single byte[]
     */
    //TODO: not tested
    public static byte[] getAsBytes(List<ByteBuffer> buffers) {
        //find total size
        int size = 0;
        for (ByteBuffer buffer : buffers) {
            size += buffer.remaining();
        }

        byte[] arr = new byte[size];

        int offset = 0;
        for (ByteBuffer buffer : buffers) {
            int len = buffer.remaining();
            buffer.get(arr, offset, len);
            offset += len;
        }

        return arr;
    }
}

Related

  1. readFromFile(Path path)
  2. readFromFile(String fileName)
  3. readFromSocket(SocketChannel channel)
  4. readFull(Reader in)
  5. readFully(final Reader input, final char[] buffer, final int offset, final int length)
  6. readFullyAndClose(InputStream input)
  7. readHeaderArea(InputStream in)
  8. readInputStream(InputStream input)
  9. readInputStreamToString(InputStream inputStream)