java nio使用例子
时间: 2023-07-11 13:45:22 浏览: 65
以下是一个简单的 Java NIO 示例代码,用于读取文件并将其内容输出到控制台:
```java
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOExample {
public static void main(String[] args) {
try {
// 创建 RandomAccessFile 对象
RandomAccessFile file = new RandomAccessFile("example.txt", "r");
// 获取 FileChannel 对象
FileChannel channel = file.getChannel();
// 创建 ByteBuffer 对象
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);
}
// 关闭通道和文件
channel.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
该示例首先创建一个 RandomAccessFile 对象,然后获取其对应的 FileChannel 对象。接着创建一个 ByteBuffer 对象,用于存储从通道读取的数据。然后通过 FileChannel 的 read() 方法将数据从通道读入缓冲区,并在 while 循环中输出到控制台。最后关闭通道和文件。