Java InputStream Copy copyStreamToByteArray(InputStream in, byte[] dest, int off, int len)

Here you can find the source of copyStreamToByteArray(InputStream in, byte[] dest, int off, int len)

Description

Reads up to len bytes from in and writes them to dest starting with off.

License

Open Source License

Parameter

Parameter Description
in input stream
dest buffer
off offset
len length

Exception

Parameter Description
IOException if reading fails

Return

number of bytes copied

Declaration

public static int copyStreamToByteArray(InputStream in, byte[] dest, int off, int len) throws IOException 

Method Source Code

//package com.java2s;
/*//from   w  w  w  . java2s.c om
 * Copyright (c) Nmote d.o.o. 2003-2015. All rights reserved.
 * See LICENSE.txt for licensing information.
 */

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

public class Main {
    /**
     * Reads up to <code>len</code> bytes from <code>in</code> and writes them
     * to <code>dest</code> starting with <code>off</code>. Returns number of
     * bytes copied. If returned number is less than len then InputStream has
     * returned end-of-file.
     *
     * @param in
     *            input stream
     * @param dest
     *            buffer
     * @param off
     *            offset
     * @param len
     *            length
     * @return number of bytes copied
     * @throws IOException
     *             if reading fails
     */
    public static int copyStreamToByteArray(InputStream in, byte[] dest, int off, int len) throws IOException {
        int r = 0;
        while (r < len) {
            int n = in.read(dest, off + r, len - r);
            if (n > 0) {
                r += n;
            } else if (n == -1) {
                break;
            } else {
                throw new IOException("Read 0 bytes from input stream");
            }
        }
        return r;
    }
}

Related

  1. copyStream(Reader in, Writer out)
  2. copyStream(Reader in, Writer out)
  3. copyStream(Reader reader, Writer writer)
  4. copyStream(ZipInputStream in, ZipEntry entry)
  5. copyStreamBytes(InputStream is)
  6. copyStreamToBytes(InputStream inputStream)
  7. copyStreamToString(InputStream input)
  8. copyStreamToString(InputStream input)
  9. copyStreamToString(InputStream input)