Skip to content

Instantly share code, notes, and snippets.

@pfmiles
Forked from awilmore/IOUtil.java
Last active September 23, 2016 10:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pfmiles/211a39417265a5f9702460b095c7042c to your computer and use it in GitHub Desktop.
Save pfmiles/211a39417265a5f9702460b095c7042c to your computer and use it in GitHub Desktop.
IO channel间互相“流”数据的方案,尽可能zero-cory
package com.awilmore.ioutils;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.SeekableByteChannel;
import java.nio.channels.WritableByteChannel;
public class IOUtil {
private static final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);
public static void flow(final ReadableByteChannel src, final WritableByteChannel dest)
throws IOException {
if (src instanceof FileChannel) {
// transferTo
FileChannel fc = (FileChannel) src;
fc.transferTo(0, fc.size(), dest);
} else if (dest instanceof FileChannel && src instanceof SeekableByteChannel) {
// transferFrom
FileChannel fc = (FileChannel) dest;
fc.transferFrom(src, 0, ((SeekableByteChannel) src).size());
} else {
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