1.2如何在文件通道读操作中使用缓冲区
完成文件通道的读操作有下列3种read方法:⑴ read(ByteBuffer buf) 将读取的文件数据存放到字节缓冲区buf中;
⑵ read(ByteBuffer[] buffers) 将读取的文件数据同时存放到字节缓冲区数组buffers的每一个元素buffers[i]中;
⑶ read(ByteBuffer[] buffers, int offset, int length) 将读取的文件数据存放到字节缓冲区数组buffers的buffers[offset]到buffer[offset+length-1]的元素中。
该3种方法从文件中读取的数据数量取决于缓冲区的位置和边界。读取的字节数据在缓冲区中存放的位置均从当前位置开始,并随着读取的字节数递增,但缓冲区的边界不会变化。它们的返回值均为实际读取的字节数,当读到文件末尾时返回-1。
另外,这3种方法均会抛出下列5种异常:①NonReadableChannelException,文件未允许读取;②ClosedChannelException,通道关闭;③AsynchronousCloseException,通道被另一个线程关闭;④ClosedByInterruptException,另一线程中断了当前线程;⑤IOException,输入输出错误。其中,只有第一种异常不需要捕获。
执行读操作后,文件位置会发生相应变化,随着读取的字节数递增。可以通过FileChannel对象的position()方法来获得文件的当前位置,也可以使用position(int)方法来指定文件的位置。position方法会抛出ClosedChannelException和其他IOException异常。
综上,读文件的基本框架如下:
// 创建文件通道
File aFile = new File(“C:/Beg Java Stuff/myFile.txt”);
FileInputStream inputFile = null;
try {
inputFile = new FileInputStream(aFile);
} catch (FileNotFoundException e) {
e.printStackTrace(System.err);
System.exit(1);
}
FileChannel inChannel = inputFile.getChannel();
// 创建缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
// 从文件中读取数据到缓冲区
try {
while (inChannel.read(buf) != -1) {
// 从缓冲区中提取数据
buf.clear();
}
System.out.println(“到达文件尾.”);
} catch (IOException e) {
e.printStackTrace(System.err);
System.exit(1);
}