Java中nio的通道和流有一些不同之处:
1.通道可以同时支持读与写,而流只能是其中之一;
2.通道支持异步读写;
3.通道的读写都通过Buffer缓冲空间进行。
通道的读写流程如下:
通道的几种实现:
- FileChannel(服务于文件)
- DatagramChannel(服务于UDP数据报)
- SocketChannel(服务于TCP 的数据读写)
- ServerSocketChannel(服务于TCP 服务端,监听请求的TCP连接,为每个连接创建一个
SocketChannel
)
基本通道使用的例子
RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw"); FileChannel inChannel = aFile.getChannel(); ByteBuffer buf = ByteBuffer.allocate(48); int bytesRead = inChannel.read(buf); while (bytesRead != -1) { System.out.println("Read " + bytesRead); buf.flip(); while(buf.hasRemaining()){ System.out.print((char) buf.get()); } buf.clear(); bytesRead = inChannel.read(buf); } aFile.close();
注意buf.flip()的调用,首先它读取数据到缓冲空间,然后flip会从缓冲空间读出来。