NIO中有关通道的所有方法以及代码演示
时间: 2024-04-11 10:27:14 浏览: 18
NIO中通道的方法包括:
1. 打开通道:
- `FileChannel.open(Path path, OpenOption... options)`:打开文件通道。
- `SocketChannel.open()`:打开套接字通道。
- `ServerSocketChannel.open()`:打开服务器套接字通道。
- `DatagramChannel.open()`:打开数据报通道。
2. 读取数据:
- `int read(ByteBuffer dst)`:从通道中读取数据到缓冲区。
- `long read(ByteBuffer[] dsts, int offset, int length)`:从通道中批量读取数据到多个缓冲区。
3. 写入数据:
- `int write(ByteBuffer src)`:将缓冲区中的数据写入通道。
- `long write(ByteBuffer[] srcs, int offset, int length)`:将多个缓冲区中的数据批量写入通道。
4. 关闭通道:
- `void close()`:关闭通道。
下面是一个简单的示例代码,演示了如何使用NIO通道进行文件读写操作:
```java
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
public class ChannelExample {
public static void main(String[] args) {
try (FileChannel channel = FileChannel.open(Path.of("input.txt"), StandardOpenOption.READ)) {
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 从通道中读取数据到缓冲区
int bytesRead = channel.read(buffer);
while (bytesRead != -1) {
buffer.flip(); // 切换缓冲区为读模式
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get()); // 处理数据
}
buffer.clear(); // 清空缓冲区
bytesRead = channel.read(buffer);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
以上代码通过打开一个文件通道,从文件中读取数据并打印到控制台。首先创建一个ByteBuffer作为缓冲区,然后循环读取数据到缓冲区,通过flip()方法切换缓冲区为读模式,处理数据后再清空缓冲区。最后关闭通道。