Java NIO 文件流读取示例 - 使用 FileChannel 和 ByteBuffer
以下是一个使用 Java NIO 读取文件流的示例代码:
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
public class NIOFileReader {
public static void main(String[] args) {
try {
RandomAccessFile file = new RandomAccessFile('test.txt', 'r');
FileChannel fileChannel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (fileChannel.read(buffer) > 0) {
buffer.flip();
while (buffer.hasRemaining()) {
System.out.print((char) buffer.get());
}
buffer.clear();
}
fileChannel.close();
file.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
该示例代码打开名为 'test.txt' 的文件,使用 FileChannel 对象读取文件流。为了读取文件,程序使用 ByteBuffer 对象分配了一个 1KB 的缓冲区。然后,使用 while 循环读取文件流,并将读取到的数据写入缓冲区。在缓冲区填充后,使用 flip() 方法将其切换到读模式,并使用 while 循环遍历缓冲区中的数据并打印它们。最后,使用 clear() 方法清除缓冲区并关闭 FileChannel 和 RandomAccessFile 对象。
原文地址: https://www.cveoy.top/t/topic/oYOm 著作权归作者所有。请勿转载和采集!