通道使用缓冲区读/写数据。缓冲区是一个固定大小的容器,我们可以其中一次写入一个数据块。通道是一种比基于流的Java输入/输出更快的方法。
要使用通道从文件中读取数据,我们需要执行以下步骤:
- 我们需要一个FileInputStream实例。FileInputStream有一个名为getChannel()的方法,该方法返回一个通道。
- 调用FileInputStream的getChannel()方法并获取通道。
- 创建ByteBuffer。ByteBuffer是一个固定大小的字节容器。
- 通道有一个read方法,我们必须提供一个ByteBuffer作为这个read方法的参数。ByteBuffer有两种模式——只读模式和只写模式。我们可以使用flip()改变模式
- 方法调用。缓冲区具有位置、限制和容量。一旦创建了一个具有固定大小的缓冲区,它的限制和容量与大小相同,并且位置从零开始。当用数据写入缓冲区时,其
- 位置逐渐增加。改变模式意味着改变位置。要从缓冲区开始读取数据,必须将位置设置为零。flip()方法更改位置
- 当我们调用通道的read方法时,它使用数据填充缓冲区。
- 如果我们需要从ByteBuffer读取数据,我们需要翻转缓冲区,将其模式改为只写模式为只读模式,然后继续从缓冲区读取数据。
- 当不再有数据可读取时,channel的read()方法返回0或者-1。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class FileChannelRead {
public static void main(String[] args) {
File inputFile = new File("hello.txt");
if (!inputFile.exists()) {
System.out.println("The input file doesn't exit.");
return;
}
try {
FileInputStream fis = new FileInputStream(inputFile);
FileChannel fileChannel = fis.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (fileChannel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
byte b = buffer.get();
System.out.print((char) b);
}
buffer.clear();
}
fileChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
日期:2020-06-02 22:15:24 来源:oir作者:oir
