Created
May 23, 2012 10:18
-
-
Save awilmore/2774441 to your computer and use it in GitHub Desktop.
Fast nio InputStream to OutputStream Copy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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