Java InputStream to String getStreamContent(InputStream stream, int bufferSize)

Here you can find the source of getStreamContent(InputStream stream, int bufferSize)

Description

get Stream Content

License

Open Source License

Declaration

public static byte[] getStreamContent(InputStream stream, int bufferSize) throws IOException 

Method Source Code

//package com.java2s;
/*******************************************************************************
 * Copyright (c) 2009, 2015 Xored Software Inc 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  . ja  v  a2  s.co  m
 *     Xored Software Inc - initial API and implementation and/or initial documentation
 *******************************************************************************/

import java.io.ByteArrayOutputStream;
import java.io.Closeable;

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

public class Main {
    /** Reads all data from the stream and closes it. */
    public static byte[] getStreamContent(InputStream stream) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[4096];
            int len = 0;
            while ((len = stream.read(buffer)) > 0) {
                output.write(buffer, 0, len);
            }
        } finally {
            safeClose(stream);
        }
        return output.toByteArray();
    }

    public static byte[] getStreamContent(InputStream stream, int bufferSize) throws IOException {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        try {
            byte[] buffer = new byte[bufferSize];
            int len = stream.read(buffer, 0, bufferSize);
            if (len > 0) {
                output.write(buffer, 0, len);
            }
        } finally {
            safeClose(stream);
        }
        return output.toByteArray();
    }

    public static void safeClose(Closeable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
        }
    }
}

Related

  1. getStreamAsString(InputStream input, String charset)
  2. getStreamAsString(InputStream is, String encoding)
  3. getStreamAsString(InputStream stream)
  4. getStreamAsString(InputStream stream, String charset)
  5. getStreamContent(InputStream is)
  6. getStreamContentAsString(InputStream is)
  7. getStreamContentAsString(InputStream is, String encoding)
  8. getStreamContents(final InputStream is)
  9. inputStream2String(InputStream in)