RandomAccessFile类的实例支持对随机访问文件的读取和写入。随机访问文件的行为类似存储在文件系统中的一个大型 byte
数组。存在指向该隐含数组的光标或索引,称为文件指针;输入操作从文件指针开始读取字节,并随着对字节的读取而前移此文件指针。如果随机访问文件以读取/写入模式创建,则输出操作也可用;输出操作从文件指针开始写入字节,并随着对字节的写入而前移此文件指针。写入隐含数组的当前末尾之后的输出操作导致该数组扩展。该文件指针可以通过
getFilePointer 方法读取,并通过 seek 方法设置。
通常,如果此类中的所有读取例程在读取所需数量的字节之前已到达文件末尾,则抛出 EOFException(是一种
IOException)。如果由于某些原因无法读取任何字节,而不是在读取所需数量的字节之前已到达文件末尾,则抛出
IOException,而不是 EOFException。需要特别指出的是,如果流已被关闭,则可能抛出
IOException。
实例:
import java.io.RandomAccessFile;
public class RandomAccessFile1 {
public static void main(String[] args) throws Exception {
Person p = new Person(1, "hello", 5.42);
RandomAccessFile raf = new RandomAccessFile("test.txt", "rw");
p.write(raf);
Person p2 = new Person();
raf.seek(0); // 让读的位置重回到文件开头
p2.read(raf);
System.out.println(p2.getId() + ", " + p2.getName() + ", " + p2.getHeight());
}
}
class Person {
int id;
String name;
double height;
public Person() {
}
public Person(int id, String name, double height) {
this.id = id;
this.name = name;
this.height = height;
}
public void write(RandomAccessFile raf) throws Exception {
raf.writeInt(this.id);
raf.writeUTF(this.name);
raf.writeDouble(this.height);
}
public void read(RandomAccessFile raf) throws Exception {
this.id = raf.readInt();
this.name = raf.readUTF();
this.height = raf.readDouble();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
}