RAF指针操作

本文详细介绍了Java中RandomAccessFile类的使用,包括如何进行读写操作、通过位移控制数据写入以及如何查看当前指针位置。示例代码展示了如何写入和读取int、long及double类型的数据,并解释了指针位置与数据读取的关系。通过seek方法可以将指针移动到文件的指定位置进行读取。
摘要由CSDN通过智能技术生成

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方法可以将指针移动到指定位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值