比特移位RandomAccessFile

时间:2014-12-03 06:06:42

标签: java bit-shift randomaccessfile

我需要将文件指针右侧的RandomAccessFile中的所有内容移位到右边四个字节,以便我可以在文件指针处写入一个整数。

这不会编译:

raf >> 16;

我打算使用readFully()(从指针开始从RAF读取字节)然后从那里开始,但是将它们读入数组并且项目的限制是我们不能使用数组。

我将如何做到这一点?

2 个答案:

答案 0 :(得分:3)

A RandomAccessFile"工作"在物理文件上,它读取和写入文件。

您不能只将字节插入某个位置。必须移动位置后的所有字节,复制以允许插入值的空间。

最有效的方法是将剩余数据读入数组,插入(写入)新值并写回数组。但是你说这是不允许的。

或者你必须使用一个循环(例如for)迭代字节并将它们写回到更大的位置(你要插入的数量:+4个字节)。

假设文件长度和当前位置是4个字节的倍数(这符合您的需要),下面是一个如何操作的示例:

public static void insert(RandomAccessFile raf, int dataToInsert)
                      throws IOException {

    // First remember insertion position:
    long insPos = raf.getFilePointer();

    // Next copy all data from this pos. For easier, go downward:
    raf.seek(raf.length() - 4);

    for (long pos = raf.getFilePointer(); pos >= insPos; pos -= 4) {
        // readInt() and writeInt() implicitly moves the file pointer
        raf.writeInt(raf.readInt());
        raf.seek(pos - 4);
    }

    // Copy done, insert new value:
    raf.seek(insPos);
    raf.writeInt(dataToInsert);
}

使用示例

RandomAccessFile raf = new RandomAccessFile("a.txt", "rw");
// Position file pointer where we want to insert:
raf.seek(4);
insert(raf, 0x41424344); // This is "ABCD" in text representation

<强>输入:

123456789012

<强>输出:

1234ABCD56789012

答案 1 :(得分:1)

由于您的目标是对整数进行排序并将其存储在文件中,因此尝试MapDB

可能是值得的。
  

MapDB提供由磁盘存储支持的并发映射,集和队列   或堆外内存。它是一个快速嵌入式Java数据库引擎   Apache许可证。

相关问题