ByteBuffer
jdk在数组的操作上提供的API很少,所以在NIO之前我们只能自己对byte[]进行一些简单处理和封装,非常麻烦。NIO提供了一系列的Buffer类,尤其是ByteBuffer进行数据处理是非常方便的,Buffer有几个属性:
- capacity:buffer的容量。
- limit:读写操作的最大索引。
- position:当前读写的索引。
- mark:用于标记某个position,当调用reset方法使得position=mark。
Channel
和IO的InputStream和OutputStream,但Channel是双向的。并和Buffer结合使用。常用的Channel:FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
下面是文件Channel的使用方式:
private static void useNio(){
RandomAccessFile aFile = null;
try {
aFile = new RandomAccessFile("/Users/sschen/Documents/SerialVersion.txt", "rw");
FileChannel inChannel = aFile.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(48);
int byteReader = inChannel.read(byteBuffer);
while (byteReader != -1) {
System.out.println("Read:" + byteReader);
byteBuffer.flip();
while (byteBuffer.hasRemaining()) {
System.out.println((char)byteBuffer.get());
}
byteBuffer.clear();
byteReader = inChannel.read(byteBuffer);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try {
aFile.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Selector
通过Selector,一个线程可以管理多个Channel,也就是多个Socket。