NIO(二)
1 直接缓冲区与非直接缓冲区
非直接缓冲区:通过allocate()方法分配缓冲区,将缓冲区建立在JVM内存中;
直接缓冲区:通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中,可以提高效率。
@Test
public void test3() {
ByteBuffer buf = ByteBuffer.allocateDirect(1024);// 分配直接缓冲区
System.out.println(buf.isDirect());//是否是直接缓冲区 true
}
allocate()方法源码:
public static ByteBuffer allocate(int capacity) {
if (capacity < 0)
throw new IllegalArgumentException();
return new HeapByteBuffer(capacity, capacity);
}
allocateDirect()方法源码:
public static ByteBuffer allocateDirect(int capacity) {
return new DirectByteBuffer(capacity);
}
DirectByteBuffer(int cap) {
super(-1, 0, cap, cap);
boolean pa = VM.isDirectMemoryPageAligned();
...省略...
}
2 通道的原理与获取
通道(Channel):由java.nio.channels包定义的。Channel表示IO源与目标打开的连接。Channel类似于传统的“流”。只不过Channel本身不能直接访问数据,Channel只能与Buffer进行交互。
![][id_4]
2.1 通道的主要实现类
java.nio.channels.Channel接口:
|--FileChannel
|--SocketChannel
|--ServerSocketChannel
|--DatagramChannel
2.2 获取通道
-
Java针对支持通道的类提供了getChannel()方法
本地IO:
FileInputStream/FileOutputStream
RandomAccessFile网络IO:
Socket
ServerSocket
DatagramSocket -
在JDK 1.7中的NIO.2 针对各个通道提供了静态方法open()
-
在JDK 1.7中的NIO.2 的Files工具类的newByteChannel()