Here you can find the source of copyStream(InputStream src, OutputStream dest)
public static void copyStream(InputStream src, OutputStream dest) throws IOException
//package com.java2s; /**/*from w ww . ja va 2 s. co m*/ * The Accord Project, http://accordproject.org * Copyright (C) 2005-2013 Rafael Marins, http://rafaelmarins.com * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; public class Main { /** * Default buffer size of 32Kb for I/O use in this library. */ public static final int DEFAULT_BUFFER_SIZE = 32 * 1024; public static void copyStream(InputStream src, OutputStream dest) throws IOException { ReadableByteChannel in = Channels.newChannel(src); WritableByteChannel out = Channels.newChannel(dest); copyChannel(in, out); in.close(); out.close(); } private static void copyChannel(ReadableByteChannel source, WritableByteChannel dest) throws IOException { ByteBuffer buffer = ByteBuffer.allocateDirect(DEFAULT_BUFFER_SIZE); while (source.read(buffer) != -1) { // prepare the buffer to be drained buffer.flip(); // write to the channel; may block dest.write(buffer); // if partial transfer, shift remainder down // if buffer is empty, same as doing clear() buffer.compact(); } // EOF will leave buffer in fill state buffer.flip(); // make sure that the buffer is fully drained while (buffer.hasRemaining()) { dest.write(buffer); } } }