RandomAccessFile 直接继承自Object:
构造方法
RandomAccessFile(File file, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件由 File 参数指定。 |
RandomAccessFile(String name, String mode) 创建从中读取和向其中写入(可选)的随机访问文件流,该文件具有指定名称。 |
import java.io.File;
import java.io.RandomAccessFile;
public class UsingRandomAccessFile {
private static String file = "F:"+File.separator+"java.txt";
public static void display() throws Exception{
RandomAccessFile rf = new RandomAccessFile(file,"r");
for(int i=0;i<7;i++){
System.out.println("Value "+i+": "+rf.readDouble());
}
System.out.println(rf.readUTF());
rf.close();
}
public static void main(String[] args) throws Exception{
RandomAccessFile rf = new RandomAccessFile(file,"rw");
for(int i=0;i<7;i++){
rf.writeDouble(i*1.414);
}
rf.writeUTF("The end of file");
rf.close();
display();
rf = new RandomAccessFile(file,"rw");
rf.seek(5*8);//设置文件指针位置,每一字节8位
rf.writeDouble(47.99);
rf.close();
display();
}
}
输出:
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 7.069999999999999
Value 6: 8.484
The end of file
Value 0: 0.0
Value 1: 1.414
Value 2: 2.828
Value 3: 4.242
Value 4: 5.656
Value 5: 47.99
Value 6: 8.484
The end of file