Java InputStream to Byte Array getBytes(InputStream in)

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

Description

Gets a byte array for the given input stream.

License

fedora commons license

Declaration

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

Method Source Code

//package com.java2s;
/*//from   w ww.  j a va  2 s.  c  om
 * This is a slightly modified version of the org.fcrepo.server.utilities.StreamUtility file.
 *
 * The original license was as follow:
 *      The contents of this file are subject to the license and copyright terms
 *      detailed in the license directory at the root of the source tree (also
 *      available online at http://fedora-commons.org/license/).
 *
 */

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**
     * Gets a byte array for the given input stream.
     */
    public static byte[] getBytes(InputStream in) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        pipeStream(in, out, 4096);
        return out.toByteArray();
    }

    /**
     * Copies the contents of an InputStream to an OutputStream, then closes
     * both.
     *
     * @param in
     *        The source stream.
     * @param out
     *        The target stram.
     * @param bufSize
     *        Number of bytes to attempt to copy at a time.
     * @throws IOException
     *         If any sort of read/write error occurs on either stream.
     */
    public static void pipeStream(InputStream in, OutputStream out, int bufSize) throws IOException {
        try {
            byte[] buf = new byte[bufSize];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                System.err.println("Unable to close stream.");
                e.printStackTrace();
            }
        }
    }
}

Related

  1. getBytes(InputStream attachment)
  2. getBytes(InputStream fis)
  3. getBytes(InputStream in)
  4. getBytes(InputStream in)
  5. getBytes(InputStream in)
  6. getBytes(InputStream in)
  7. getBytes(InputStream in, int length, int BUF_SIZE)
  8. getBytes(InputStream in, OutputStream out)
  9. getBytes(InputStream input)