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

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 it
			desc.write(buffer);// writer the buffer, may not write on letter or
								// some
			buffer.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);

	}
}

你可能感兴趣的:(从一个缓冲到另一个缓冲的输出)