示例
Channel使用Buffer读取/写入数据。缓冲区是固定大小的容器,我们可以在其中一次写入一个数据块。Channel比基于流的I / O快得多。
要使用文件读取数据,Channel我们需要执行以下步骤:我们需要一个实例FileInputStream。FileInputStream有一个名为getChannel()的方法,该方法返回一个Channel。
调用FileInputStream的getChannel()方法并获取Channel。
创建一个ByteBuffer。ByteBuffer是固定大小的字节容器。
Channel具有读取方法,我们必须提供ByteBuffer作为此读取方法的参数。ByteBuffer有两种模式-只读和只写。我们可以使用flip()方法调用来更改模式。缓冲区具有位置,限制和容量。创建具有固定大小的缓冲区后,其限制和容量与该大小相同,并且位置从零开始。当缓冲区写入数据时,其位置逐渐增加。改变模式意味着改变位置。要从缓冲区的开头读取数据,我们必须将位置设置为零。flip()方法改变位置
当我们调用的read方法时Channel,它会使用数据填充缓冲区。
如果需要从读取数据ByteBuffer,则需要翻转缓冲区以将其模式从只读模式更改为只读模式,然后继续从缓冲区读取数据。
当不再有要读取的数据时,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();
}
}
}