JavaNIO-通道
Channel
这里的Channel接口很细。一个Channel能做什么呢?
package java.nio.channels; public interface Channel { public boolean isOpen( ); public void close( ) throws IOException; }public interface ReadableByteChannel extends Channel {public int read (ByteBuffer dst) throws IOException;}public interface WritableByteChannel extends Channel { public int write (ByteBuffer src) throws IOException;}public interface ByteChannel extends ReadableByteChannel, WritableByteChannel {}package shaoxin.nio;import java.io.IOException;import java.nio.ByteBuffer;import java.nio.channels.Channel;import java.nio.channels.Channels;import java.nio.channels.ReadableByteChannel;import java.nio.channels.WritableByteChannel;public class ChannelCopy {public static void main(String []args) throws Exception{ChannelCopy copyc = new ChannelCopy();ReadableByteChannel readChannel = Channels.newChannel(System.in);WritableByteChannel writeChannel = Channels.newChannel(System.out);copyc.copyChannel(readChannel, writeChannel);readChannel.close();writeChannel.close();}public void copyChannel(ReadableByteChannel from ,WritableByteChannel to)throws Exception{ByteBuffer buffer = ByteBuffer.allocate(1024);buffer.flip();while(from.read(buffer)!=-1){buffer.flip();to.write(buffer);buffer.compact();}buffer.flip();while(buffer.hasRemaining()){to.write(buffer);}}public void copyChannel2(ReadableByteChannel from ,WritableByteChannel to)throws IOException{ByteBuffer buffer = ByteBuffer.allocate(1024);while(from.read(buffer)!=-1){buffer.flip();while(buffer.hasRemaining()){to.write(buffer);}buffer.clear();}}}public interface ScatteringByteChannel extends ReadableByteChannel {public long read (ByteBuffer [] dsts) throws IOException;public long read (ByteBuffer [] dsts, int offset, int length) throws IOException; }public interface GatheringByteChannel extends WritableByteChannel{ public long write(ByteBuffer[] srcs) throws IOException; public long write(ByteBuffer[] srcs, int offset, int length) throws IOException; }ByteBuffer header = ByteBuffer.allocateDirect (10); ByteBuffer body = ByteBuffer.allocateDirect (80); ByteBuffer [] buffers = { header, body }; int bytesRead = channel.read (buffers);switch (header.getShort(0)) { case TYPE_PING: break; case TYPE_FILE: body.flip( ); fileChannel.write (body); break; default: logUnknownPacket (header.getShort(0), header.getLong(2), body); break; }