Here you can find the source of copyStream(final InputStream aInStream, final OutputStream aOutStream)
InputStream
and OutputStream
.
Parameter | Description |
---|---|
aInStream | The stream from which to read |
aOutStream | The stream from which to write |
Parameter | Description |
---|---|
IOException | If there is trouble reading or writing |
public static void copyStream(final InputStream aInStream, final OutputStream aOutStream) throws IOException
//package com.java2s; /**/* ww w .ja v a 2s .c o m*/ * Licensed under the GNU LGPL v.2.1 or later. */ import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; public class Main { /** * Writes from an input stream to an output stream; you're responsible for closing the <code>InputStream</code> * and <code>OutputStream</code>. * * @param aInStream The stream from which to read * @param aOutStream The stream from which to write * @throws IOException If there is trouble reading or writing */ public static void copyStream(final InputStream aInStream, final OutputStream aOutStream) throws IOException { final BufferedOutputStream outStream = new BufferedOutputStream(aOutStream); final BufferedInputStream inStream = new BufferedInputStream(aInStream); final ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); final byte[] buffer = new byte[1024]; int bytesRead = 0; while (true) { bytesRead = inStream.read(buffer); if (bytesRead == -1) { break; } byteStream.write(buffer, 0, bytesRead); } outStream.write(byteStream.toByteArray()); outStream.flush(); } /** * Writes a file to an output stream. You're responsible for closing the <code>OutputStream</code>; the input * stream is closed for you since just a <code>File</code> was passed in. * * @param aFile A file from which to read * @param aOutStream An output stream to which to write * @throws IOException If there is a problem reading or writing */ public static void copyStream(final File aFile, final OutputStream aOutStream) throws IOException { final FileInputStream input = new FileInputStream(aFile); final FileChannel channel = input.getChannel(); final byte[] buffer = new byte[256 * 1024]; final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer); try { for (int length = 0; (length = channel.read(byteBuffer)) != -1;) { aOutStream.write(buffer, 0, length); byteBuffer.clear(); } } finally { input.close(); } } }