Java InputStream Read All readall(InputStream in, byte[] buffer, int offset, int len)

Here you can find the source of readall(InputStream in, byte[] buffer, int offset, int len)

Description

Receives data.

License

Open Source License

Parameter

Parameter Description
in The stream of data which comes via network.
buffer The target buffer.
offset The start offset in array buffer at which the data is written.
len The maximum number of bytes to read.

Exception

Parameter Description
IOException thrown when interrupted during busy waiting

Return

The number of bytes actually read is returned as an integer.

Declaration

public static int readall(InputStream in, byte[] buffer, int offset, int len) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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

public class Main {
    private static final int POLL_INTERVAL = 50;

    /**//  www.ja  v a 2  s  .c o m
     * Receives data. Will read exactly the given number of bytes. Only if the
     * end-of-file is reached, it might be that we return less bytes.
     *
     * @param in The stream of data which comes via network.
     * @param buffer The target buffer.
     * @param offset The start offset in array buffer at which the data is written.
     * @param len The maximum number of bytes to read.
     * @return The number of bytes actually read is returned as an integer.
     * @throws IOException thrown when interrupted during busy waiting
     */
    public static int readall(InputStream in, byte[] buffer, int offset, int len) throws IOException {
        // use polling to read all data
        int total = 0;
        for (;;) {
            int received = in.read(buffer, offset, len);
            if (received < 0) {
                return total;
            }
            total += received;
            offset += received;
            len -= received;
            if (len == 0) {
                return total;
            }
            try {
                Thread.sleep(POLL_INTERVAL);
            } catch (InterruptedException e) {
                throw new IOException("Interrupted during busy waiting", e);
            }
        }
    }
}

Related

  1. readAll(InputStream in)
  2. readAll(InputStream in)
  3. readAll(InputStream in)
  4. readAll(InputStream in)
  5. readAll(InputStream in, byte[] buffer, int off, int len)
  6. readAll(InputStream inputStream)
  7. readAll(InputStream is)
  8. readAll(InputStream is, byte[] buffer, int offset, int length)
  9. readAll(InputStream stream)