Skip to content

Instantly share code, notes, and snippets.

@awilmore
Created May 23, 2012 10:18
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save awilmore/2774441 to your computer and use it in GitHub Desktop.
Save awilmore/2774441 to your computer and use it in GitHub Desktop.
Fast nio InputStream to OutputStream Copy
package com.awilmore.ioutils;
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 IOUtil {
public static void fastCopy(final InputStream src, final OutputStream dest) throws IOException {
final ReadableByteChannel inputChannel = Channels.newChannel(src);
final WritableByteChannel outputChannel = Channels.newChannel(dest);
fastCopy(inputChannel, outputChannel);
}
public static void fastCopy(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
while(src.read(buffer) != -1) {
buffer.flip();
dest.write(buffer);
buffer.compact();
}
buffer.flip();
while(buffer.hasRemaining()) {
dest.write(buffer);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment