<Java>RandomAccessFile在文件中定位写入

如果在Java中想在写入的文件中进行定位操作,可以使用随机访问类RandomAccessFile进行定位写覆盖,使用其提供的seek方法,根据写入的数据类型计算大小进行定位。
写入文件的方式是byte类型。所以进行了int与byte类型的转换,由于数据类型小,所以只转换了16位(int 32位,short16位)。

public class FileTest {
    private String fileString = "test.dat";

    public void test()
    {
        try {
            File file = new File(fileString);
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            RandomAccessFile fileAccessFile = new RandomAccessFile(file,"rw");
            int[] testString = {1,2,3};
            int [] outInt = new int[3];
            byte[] outByte = new byte[6];
            byte[] outByte2 = new byte[12];
            int[] outInt2 = new int[6];
            outByte = int2byte(testString, 3);  
            for(int i:testString)
                System.out.println("testString="+String.valueOf(i));

            fileOutputStream.write(outByte);

            fileAccessFile.seek(2);//在第3个位置进行插入覆盖
            fileAccessFile.write(outByte);

            FileInputStream fileInputStream = new FileInputStream(file);
            fileInputStream.read(outByte2);
            outInt2 = byte2int(outByte2, 6);

            fileOutputStream.close();
            fileAccessFile.close();
            fileInputStream.close();

            for(int i:outInt2)
                System.out.println("outInt2="+String.valueOf(i));

        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private byte[] int2byte(int[] array,int len)
    {
        byte[] out = new byte[len*2]; 
        for(int i=0;i<len;i++)
        {
            out[2*i] = (byte)(array[i]&0xff);
            out[2*i + 1] = (byte)(array[i]>>8);
        }
        return out;
    }

    private int[] byte2int(byte[] array,int len)
    {
        int[] out = new int[len];
        for(int i=0;i<len;i++)
        {
            out[i] = (int)((array[2*i+1]<<8) | (array[2*i]&0xff));
        }
        return out;
    }

}

输出结果,可以看出第二个数字往后被覆盖,fileOutputstream只能进行顺序写入,不会记录随机访问的位置,如果再进行fileoutputstream写入,则是其之前结束的位置再写入。

testString=1
testString=2
testString=3
outInt2=1
outInt2=1
outInt2=2
outInt2=3
outInt2=0
outInt2=0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值