RandomAccessFile 可以实现两个作用:
- 实现对一个文件做读和写的操作。
可以访问文件的任意位置。不像其他流只能按照先后顺序读取
在开发某些客户端软件时,经常用到这个功能强大的可以”任意操作文件内容”的类。比 如,软件的使用次数和使用日期,可以通过本类访问文件中保存次数和日期的地方进行比对 和修改。 Java 很少开发客户端软件,所以在 Java 开发中这个类用的相对
学习这个流需掌握三个核心方法 :RandomAccessFile(String name, String mode) name 用来确定文件; mode 取 r(读)或 rw(可读写),通过 mode 可以确定流对文件的
- seek(long a) 用来定位流对象读写文件的位置,a 确定读写位置距离文件开头的字节个数
- getFilePointer() 获得流的当前读写位置
import java.io.RandomAccessFile;
public class RandomAccessFileDemo {
public static void main(String[] args) {
RandomAccessFile randomAccessFile=null;
try{
randomAccessFile=new RandomAccessFile("d:/javaStudy/javaworkspace/random.txt","rw");
//将若干数据写到文件中
int[] arr=new int[]{10,20,30,40,50,60,70,80,90,100};
for(int i=0;i<arr.length;i++){
randomAccessFile.writeInt(arr[i]);
}
randomAccessFile.seek(4); //从指定字节位置开始读,默认0
System.out.println(randomAccessFile.readInt());
//间隔读取数据
for(int i=0;i<10;i+=2){
randomAccessFile.seek(i*4);
System.out.print(randomAccessFile.readInt()+"\t");
}
System.out.println();
//在第八个字节位置插入一个新的数据45,替换之前的数据30
randomAccessFile.seek(8);
randomAccessFile.writeInt(45);
for(int i=0;i<10;i+=2){
randomAccessFile.seek(i*4);
System.out.print(randomAccessFile.readInt()+"\t");
}
}catch (Exception e){
e.printStackTrace();
}finally {
try{
if(randomAccessFile!=null){
randomAccessFile.close();
}
}catch (Exception e){
e.printStackTrace();
}
}
}
}