Java NIO的通道类似流,但又有些不同:
- 既可以从通道中读取数据,又可以写数据到通道。但流的读写通常是单向的。
- 通道可以异步地读写。
- 通道中的数据总是要先读到一个Buffer,或者总是要从一个Buffer中写入。
正如上面所说,从通道读取数据到缓冲区,从缓冲区写入数据到通道。如下图所示:
Channel的实现
这些是Java NIO中最重要的通道的实现:
- FileChannel
- DatagramChannel
- SocketChannel
- ServerSocketChannel
FileChannel 从文件中读写数据。
DatagramChannel 能通过UDP读写网络中的数据。
SocketChannel 能通过TCP读写网络中的数据。
ServerSocketChannel可以监听新进来的TCP连接,像Web服务器那样。对每一个新进来的连接都会创建一个SocketChannel。
基本的 Channel 示例
下面是一个使用FileChannel读取数据到Buffer中的示例:
package lime.tij._018._010._000; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; /** * @Author liangmy * @Date 2019/9/18 */ public class GetChannel { public static final int BSIZE = 1024; public static final String filePathIn = "/Users/liangmy/ideaProjects/lime/src/main/java/lime/tij/_018/_010/_000/GetChannel.java"; public static final String filePathOut = "/Users/liangmy/ideaProjects/lime/src/main/java/lime/tij/_018/_010/_000/GetChannel.out"; public static void main(String[] args) throws IOException { // Write a file FileChannel fileChannel = new FileOutputStream(filePathOut).getChannel(); fileChannel.write(ByteBuffer.wrap("some text".getBytes())); fileChannel.close(); // Add to the end of the file fileChannel = new RandomAccessFile(filePathOut, "rw").getChannel(); fileChannel.position(fileChannel.size()); // Move to the end : fileChannel.write(ByteBuffer.wrap("\n".getBytes())); fileChannel.write(ByteBuffer.wrap("some more".getBytes())); fileChannel.close(); // Read the file : fileChannel = new FileInputStream(filePathIn).getChannel(); ByteBuffer byteBuffer = ByteBuffer.allocate(BSIZE); fileChannel.read(byteBuffer); byteBuffer.flip(); while (byteBuffer.hasRemaining()) { System.out.print((char) byteBuffer.get()); } } } |
注意 buf.flip() 的调用,首先读取数据到Buffer,然后反转Buffer,接着再从Buffer中读取数据。下一节会深入讲解Buffer的更多细节。