Channel
FileChannel<br>只有阻塞模式
创建:getChannel()方法
FileInputStream
读文件,构造器传入File 文件或String 文件名
FileOutputStream
写文件,构造器传入File或String文件名
RandomAccessFile
读写文件,构造器传入File或String文件名,String 读/写模式
方法
读文件,写入ByteBuffer
inchannel.read(buf)
读ByteBuffer,写入文件
outchannal.write(buf)
scatter,将读取的数据写入多个buffer
inchannel.read(ByteBuffer[] dests)
gather,将多个buffer的数据写入同一个Channel
outchannel.write(ByteBuffer[] dsts)
transferFrom(ReadableByteChannel src,
long position, long count)
long transferTo(long position, long count,
WritableByteChannel target)
SelectableChannel<br>有非阻塞模式
DatagramChannel
SocketChannel
ServerSocketChannel
abstract class Buffer
子类
abstract class ByteBuffer
创建
创建HeapByteBuffer对象
特点
这种缓冲区是分配在Java虚拟机的堆上,直接由JVM负责垃圾回收
heapbuffer对象写入channal,需中转到内核缓冲区(创建临时directbuffer)——速度慢
static ByteBuffer allocate(int capacity)
static ByteBuffer wrap(byte[] array)
创建DirectByteBuffer对象
特点
通过JNI在Java的虚拟机外的内存中分配了一块缓冲区
创建、释放代价高,但速度快
static ByteBuffer allocateDirect(int capacity)
读写
读Buffer
byte tmp = buf.get()
方法
Buffer compact()
未读完继续写:清除已经读过的数据,任何未读的数据都被移到<br>缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。
CharBuffer
DoubleBuffer
...
字段
约束:mark<=position<=limit<=capacity
mark
-1,丢弃状态
Buffer mark()——将mark设置为pos的值
limit
表示之前写进了多少个byte、char...
方法
Buffer flip()
准备读:lim置为之前写到的pos处,pos置0,mark置-1
Buffer rewind()
重读:pos置0,mark置-1
Buffer clear()
准备写:清空缓冲区,pos置0,lim置cap,mark置-1
Buffer reset()
重置:pos置mark
Buffer mark()
标记:mark置pos
Selectors
意义:使用Selector能够处理多个通道
创建:Selector selector = Selector.open();
注册通道:SelectionKey key = channel.register(selector, 感兴趣的事件的int);
读就绪OP_READ=1<<0
写就绪OP_WRITE=1<<2
连接就绪OP_CONNECT=1<<3
接收就绪OP_ACCEPT=1<<4
就绪通道数:上次调用select()方法后变成就绪状态的通道数
int select()——阻塞到至少有一个通道在注册的事件上就绪
int select(long timeout)——最长会阻塞timeout毫秒
int selectNow()——不会阻塞,不管什么通道就绪都立刻返回
就绪通道相应的Selectionkey集合:Set<SelectionKey> selectedKeys()
wakeUp()、close()
SelectionKey
创建:SelectionKey key = channel.register(selector, 感兴趣的事件的int);
interest集合:感兴趣事件的集合,int interestSet = selectionKey.interestOps(); <br>
ready集合:就绪事件的集合,int readySet = selectionKey.readyOps();
Channel channel = selectionKey.channel(); <br>
Selector selector = selectionKey.selector();
附加对象
selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment(); <br>