Java InputStream to OutputStream copyStream(final InputStream input, final OutputStream output, long count)

Here you can find the source of copyStream(final InputStream input, final OutputStream output, long count)

Description

Copies count bytes from input to output.

License

Open Source License

Declaration

public static void copyStream(final InputStream input, final OutputStream output, long count)
        throws IOException 

Method Source Code


//package com.java2s;

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

public class Main {
    /**/*from w ww  .j ava 2 s  .  co  m*/
     * Copies count bytes from input to output. If the count is negative, bytes
     * are copied until the end of stream.
     */
    public static void copyStream(final InputStream input, final OutputStream output, long count)
            throws IOException {
        final byte[] buffer = new byte[64 * 1024];

        // Easier to duplicate loops than to unify control behavior
        if (count < 0) {
            int read;
            while ((read = input.read(buffer)) != -1) {
                output.write(buffer, 0, read);
            }
        } else {
            while (count > 0) {
                // Safe to cast to int because it's less than the buffer size
                int maxToRead = count > buffer.length ? buffer.length : (int) count;

                final int read = input.read(buffer, 0, maxToRead);

                if (read == -1) {
                    return;
                }

                count -= read;

                output.write(buffer, 0, read);
            }
        }
    }
}

Related

  1. copyStream(ByteArrayOutputStream source, ByteArrayOutputStream target)
  2. copyStream(final InputStream in, final OutputStream out)
  3. copyStream(final InputStream in, final OutputStream out)
  4. copyStream(final InputStream in, final OutputStream out, final int bufferSize)
  5. copyStream(final InputStream in, final OutputStream out, int iMax)
  6. copyStream(final InputStream inputStream, final OutputStream out)
  7. copyStream(final InputStream inputStream, final OutputStream outputStream)
  8. copyStream(final InputStream inputStream, final OutputStream outputStream)
  9. copyStream(final InputStream inputStream, final OutputStream outputStream)