Java InputStream to Byte Array inputStreamToBytes(InputStream in)

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

Description

Read all the data from the input stream up until the first end of file character, add this data to a byte array, and close the input stream; returns the byte array

License

Open Source License

Declaration

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

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2001, 2007 IBM Corporation and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors://from   www . j a  va 2  s .c o  m
 * IBM Corporation - initial API and implementation
 *******************************************************************************/

import java.io.ByteArrayOutputStream;

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

import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class Main {
    /**
     * Read all the data from the input stream up until the first end of file character, add this
     * data to a byte array, and close the input stream; returns the byte array
     */
    public static byte[] inputStreamToBytes(InputStream in)
            throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        copy(in, out);
        return out.toByteArray();
    }

    /**
     * Copy all the data from the input stream to the output stream up until the first end of file
     * character, and close the two streams
     */
    public static void copy(InputStream in, OutputStream out)
            throws IOException {
        byte[] buffer = new byte[1024];
        try {
            int n = in.read(buffer);
            while (n > 0) {
                out.write(buffer, 0, n);
                n = in.read(buffer);
            }
        } finally {
            if (!(in instanceof ZipInputStream))
                in.close();
            if (!(out instanceof ZipOutputStream))
                out.close();
        }
    }
}

Related

  1. inputStreamToByteArrayOutputStream(final InputStream is)
  2. inputStreamToBytes(final InputStream aInputStream)
  3. inputStreamToBytes(final InputStream ins)
  4. inputStreamToBytes(InputStream in)
  5. inputStreamToBytes(InputStream in)
  6. inputStreamToBytes(InputStream is)
  7. loadByteCode(String name, final InputStream is)