Java InputStream to OutputStream copyStreams(final InputStream input, final OutputStream output)

Here you can find the source of copyStreams(final InputStream input, final OutputStream output)

Description

This method copies the contents of an input stream to an output stream.

License

Open Source License

Parameter

Parameter Description
input The input stream to read
output The output stream to write

Exception

Parameter Description
IOException If anything fails.

Return

The total number of bytes transfered between the streams

Declaration

public static int copyStreams(final InputStream input, final OutputStream output) throws IOException 

Method Source Code


//package com.java2s;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    /**/* w ww.j  ava2s  . co  m*/
     * The amount of memory that we will reserve to read files.
     */
    protected static final int BUFFER_SEGMENT_LENGTH = 4096;

    /**
     * This method copies the contents of an input stream to an output stream. The streams are not closed after the
     * method completes.
     * 
     * @param input
     *            The input stream to read
     * @param output
     *            The output stream to write
     * @return The total number of bytes transfered between the streams
     * @throws IOException
     *             If anything fails.
     */
    public static int copyStreams(final InputStream input, final OutputStream output) throws IOException {
        int amtRead = 0;
        int totalLength = 0;
        byte[] segment = new byte[BUFFER_SEGMENT_LENGTH];
        amtRead = input.read(segment, 0, segment.length);
        while (amtRead != -1) {
            totalLength += amtRead;
            output.write(segment, 0, amtRead);
            amtRead = input.read(segment, 0, segment.length);
        }

        return totalLength;
    }
}

Related

  1. copyStreamFully(InputStream in, OutputStream out, int length)
  2. copyStreamIoe(final InputStream is, final OutputStream os)
  3. copyStreamNoClose(InputStream in, OutputStream out)
  4. copyStreamPortion(java.io.InputStream inputStream, java.io.OutputStream outputStream, int portionSize, int bufferSize)
  5. copyStreams(final InputStream in, final OutputStream out)
  6. copyStreams(InputStream from, OutputStream to, int blockSize)
  7. copyStreams(InputStream in, OutputStream out)
  8. copyStreams(InputStream in, OutputStream out)
  9. copyStreams(InputStream in, OutputStream out)