RandomAccessFile可以对文件进行读写操作,通过指针可以控制读写的位置。
写入操作
public class RafSeekDemo {
public static void main(String[] args) throws IOException {
RandomAccessFile raf = new RandomAccessFile("dat.dat","rw");
//获取当前指针位置
long pos = raf.getFilePointer();
System.out.println(pos);
int max = Integer.MAX_VALUE;
/*
* int类型4字节,每次写入都是低八位。
* vvvvvvvv
* 01111111 11111111 11111111 11111111
* 需要将高八位内容移动到低八位进行写入
* */
raf.write(max >>> 24); //移动三个8位
System.out.println("pos:"+raf.getFilePointer());
raf.write(max >>> 16); //移动两个8位
raf.write(max >>> 8);
raf.write(max);
System.out.println("pos:"+raf.getFilePointer());
//直接写int数据
raf.writeInt(max); //writeInt也是通过位移的方法进行写入的
raf.writeLong(13L);
System.out.println("pos:"+raf.getFilePointer());
raf.writeDouble(123.123);
System.out.println("pos:"+raf.getFilePointer()); //此时指针在下标24的位置,实际上0-23个数据,24为0。所以此时为-1
}
}
- int类型4字节,每次写入都是低八位。需要将高八位内容移动到低八位进行写入。
- 利用writeInt可直接写入,源码意识利用了位移方法。
- raf.getFilePointer();方法可以查看当前指针位置。
读取文件
//指针移动到指定位置
//void seek(long pos);
raf.seek(0);
//读取文件数据
int data = raf.read();
System.out.println(data);
raf.seek(4);
int i = raf.readInt();
long l = raf.readLong();
double d = raf.readDouble();
System.out.println(i); //int最大值
System.out.println(l);
System.out.println(d);
- 写入后直接调用read方法,结果为-1。此时指针在下标24的位置,实际上0-23个数据,24为0。所以此时为-1
- 利用seek方法可以将指针移动到指定位置。