Java.io.RandomAccessFile.readFully() 方法
描述
java.io.RandomAccessFile.readFully(byte[] b,int off,int len) 方法从当前文件指针开始将该文件中的 len 个字节准确地读取到字节数组中。 此方法从文件中重复读取,直到读取请求的字节数。
声明
以下是 java.io.RandomAccessFile.readFully() 方法的声明。
public final void readFully(byte[] b,int off,int len)
参数
b − 读取数据的缓冲区。
off − 数据的起始偏移量。
len − 要读取的字节数。
返回值
此方法不返回值。
异常
IOException − 如果发生 I/O 错误。
EOFException − 如果此文件在读取所有字节之前到达末尾。
示例
下面的例子展示了 java.io.RandomAccessFile.readFully() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class RandomAccessFileDemo {
public static void main(String[] args) {
try {
// create a string and a byte array
String s = "Hello world";
// create a new RandomAccessFile with filename test
RandomAccessFile raf = new RandomAccessFile("c:/test.txt", "rw");
// write something in the file
raf.writeUTF(s);
// set the file pointer at 0 position
raf.seek(0);
// create an array equal to the length of raf
byte[] arr = new byte[10];
// read the file
raf.readFully(arr, 3, 7);
// create a new string based on arr
String s2 = new String(arr);
// print it
System.out.println("" + s2);
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
假设我们有一个文本文件c:/test.txt,其内容如下。 该文件将用作我们示例程序的输入 −
ABCDE
让我们编译并运行上面的程序,这将产生下面的结果 −
Hello

