Java InputStream to Byte Array getBytes(InputStream stream)

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

Description

Return the contents of an InputStream as a byte arrary

License

Apache License

Parameter

Parameter Description
stream an InputStream

Exception

Parameter Description
IOException an exception

Return

the content from InputStream stream as a byte array

Declaration

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

Method Source Code

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

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

import java.io.OutputStream;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;

public class Main {
    /**//from  ww  w . j a v a 2s.  c  o m
     * Return the contents of an InputStream as a byte arrary
     * @param stream an InputStream
     * @return the content from InputStream stream as a byte array
     * @throws IOException 
     */
    public static byte[] getBytes(InputStream stream) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        copy(stream, baos);
        return baos.toByteArray();
    }

    public static void copy(InputStream is, OutputStream os)
            throws IOException {
        byte b[] = new byte[32000];
        int len = is.read(b);
        while (len > -1) {
            os.write(b, 0, len);
            len = is.read(b);
        }
    }

    public static void copy(Reader reader, Writer writer)
            throws IOException {
        char buf[] = new char[4000];
        int len = reader.read(buf);
        while (len > -1) {
            writer.write(buf, 0, len);
            len = reader.read(buf);
        }
    }

    public static void copy(Reader reader, OutputStream os)
            throws IOException {
        StringWriter writer = new StringWriter();
        copy(reader, writer);
        os.write(writer.toString().getBytes());
    }
}

Related

  1. getBytes(InputStream is)
  2. getBytes(InputStream is)
  3. getBytes(InputStream is)
  4. getBytes(InputStream is, int max_len)
  5. getBytes(InputStream stream)
  6. getBytesFromInputStream(InputStream inputStream)
  7. getBytesFromInputStream(InputStream inputStream)
  8. getBytesFromInputStream(InputStream inputStream)
  9. getBytesFromInputStream(InputStream is)