Java Dump Stream dumpStream(InputStream in, PrintStream dump, boolean closeIn)

Here you can find the source of dumpStream(InputStream in, PrintStream dump, boolean closeIn)

Description

dump Stream

License

GNU General Public License

Declaration

public static InputStream dumpStream(InputStream in, PrintStream dump, boolean closeIn) throws IOException 

Method Source Code


//package com.java2s;
/* ***** BEGIN LICENSE BLOCK *****
 * Version: GPL 2.0/* w w  w.  j  a va2s  .  c o  m*/
 *
 * The contents of this file are subject to the GNU General Public
 * License Version 2 or later (the "GPL").
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * The Initial Developer of the Original Code is
 *   MiniG.org project members
 *
 * ***** END LICENSE BLOCK ***** */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

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

public class Main {
    private static final int BUFF_SIZE = 100000;

    public static InputStream dumpStream(InputStream in, PrintStream dump, boolean closeIn) throws IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            transfer(in, out, closeIn);
            dump.println("-- stream dump start --");
            dump.println(out.toString());
            dump.println("-- stream dump end --");
        } catch (Throwable t) {
            throw new IOException(t);
        }
        return new ByteArrayInputStream(out.toByteArray());
    }

    /**
     * Fast stream transfer method
     * 
     * @param in
     * @param out
     * @throws IOException
     */
    public static void transfer(InputStream in, OutputStream out, boolean closeIn) throws IOException {
        final byte[] buffer = new byte[BUFF_SIZE];

        try {
            while (true) {
                int amountRead = in.read(buffer);
                if (amountRead == -1) {
                    break;
                }
                out.write(buffer, 0, amountRead);
            }
        } finally {
            if (closeIn) {
                in.close();
            }
            out.flush();
            out.close();
        }
    }
}

Related

  1. dumpInputStream(InputStream is, PrintStream p)
  2. dumpInputStream(InputStream stream)
  3. dumpInputStreamAsString(InputStream is)
  4. dumpInputStreamIntoString(InputStream f, String encoding)
  5. dumpMap(PrintStream out, Map Values)
  6. dumpStream(InputStream in, String file)
  7. dumpStreamAndReOffer(InputStream is)
  8. dumpStreamToFile(InputStream is, String filename)
  9. dumpStreamToStream(InputStream is, OutputStream os)