首页 > java RandomAccessFile 覆盖数据

java RandomAccessFile 覆盖数据

下面的一个测试程序来说明我的问题:

RandomAccessFile r = new RandomAccessFile("heihei.txt", "rw");

r.writeChar('a');
r.writeChar('b');
r.writeChar('c');
//这样文件的内容不就应该是abc了吗?

r.seek(2); //指针设置在a后.
r.writeChar('d'); //文件理应变成adbc,但貌似不是这么回事,如下

StringBuffer strBuf = new StringBuffer();
r.seek(0); //指针归回初始位置
strBuf.append(r.readChar()); 
strBuf.append(r.readChar());
strBuf.append(r.readChar()); 
strBuf.append(r.readChar());

System.out.println(strBuf); //结果是adc

怎么才能防止覆盖啊?


答案是不能。
RandomAccessFile

其中这一句话

output operations write bytes starting at the file pointer and advance
the file pointer past the bytes written

RandomAccessFile 将文件视为一个byte数组,它修改其中某个位置的值的行为就是,将第i个位置的值写为新的值,然后将指针指向后一个元素。

可以看出,这个类不会帮你完成所有剩下的值进行移位的功能。所以如果你需要完成“插入”的功能,需要自己把数组的后续内容读取出来,重新按顺序写入文件。

stackoverflow参考:

  1. Inserting text in middle using RandomAccessFile removes some text after that
【热门文章】
【热门文章】