从一个缓冲到另一个缓冲的输出

来源:互联网 发布:工程计算器软件下载 编辑:程序博客网 时间:2024/05/21 17:01
package langs;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Channels;import java.nio.channels.ReadableByteChannel;import java.nio.channels.WritableByteChannel;public class ChannelTest {private static final int _M = 1024 * 1024;private static final ByteBuffer buffer = ByteBuffer.allocate(1 * _M);/** *  * 标准将buffer 从一个缓冲输出到另一个缓冲 *  * @param src * @param desc * @throws IOException */public static void copy(ReadableByteChannel src, WritableByteChannel desc)throws IOException {while (src.read(buffer) != -1 || buffer.position() == 0) {buffer.flip(); // must do itdesc.write(buffer);// writer the buffer, may not write on letter or// somebuffer.compact(); // put the left buffer into the front}}public static void main(String args[]) throws IOException {ReadableByteChannel reader = Channels.newChannel(System.in);WritableByteChannel writer = Channels.newChannel(System.out);copy(reader, writer);}}

原创粉丝点击