-
-
Save pfmiles/211a39417265a5f9702460b095c7042c to your computer and use it in GitHub Desktop.
IO channel间互相“流”数据的方案,尽可能zero-cory
This file contains hidden or 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.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