2

我已经MappedBytes为一个文件创建了一个实例,该文件用作不同 Java 进程之间的共享缓存。

我希望能够从原始文件中分离出额外的 MappedByte 实例(或 ByteBuffer 或任何其他实例),这些实例提供对底层文件子集的直接读/写访问。

我今天花了很多时间尝试不同的方法,但选项如subBytes(),rawCopy()并且copyTo()似乎都是创建底层文件的本地副本,而不是直接访问文件。

例如:

File tmpFile = new File(System.getProperty("java.io.tmpdir"), "data.dat");
MappedFile mappedFile = MappedFile.mappedFile(tmpfile, 1000, 100, 10, false);
MappedBytes original = MappedBytes.mappedBytes(mappedFile);
original.zeroOut(0, 1000);

original.writeInt(0, 1234);
BytesStore copy = original.bytesStore().subBytes(0, 200);

// Print out the int in the two BytesStores.
// This shows that the copy has the same contents of the original.
System.out.println("Original(0): " + original.readInt(0));
System.out.println("Copy(0): " + copy.readInt(0));

// Now modify the copy and print out the new int in the two BytesStores again.
copy.writeInt(50, 4321);
System.out.println("Original(50): " + original.readInt(50));
System.out.println("Copy(50): " + copy.readInt(50));

产生输出:

Original(0): 1234
Copy(0): 1234
Original(50): 0
Copy(50): 4321

副本已被修改,但不是原件。我想修改原始文件,chronicle-bytes 可以这样做吗?

谢谢你的帮助,乔希。

4

1 回答 1

0

这是一个独立的测试,我认为它的行为方式符合您的需要。

@Test
public void multiBytes() throws FileNotFoundException {
    String tmpfile = OS.TMP +  "/data.dat";
    MappedFile mappedFile = MappedFile.mappedFile(new File(tmpfile), 64 << 10);
    MappedBytes original = MappedBytes.mappedBytes(mappedFile);
    original.zeroOut(0, 1000);

    original.writeInt(0, 1234);

    PointerBytesStore pbs = new PointerBytesStore();
    pbs.set(original.addressForRead(50), 100);

    // Print out the int in the two BytesStores.
    // This shows that the copy has the same contents of the original.
    System.out.println("Original(0): " + original.readInt(0));
    System.out.println("PBS(0): " + pbs.readInt(0));

    // Now modify the copy and print out the new int in the two BytesStores again.
    pbs.writeInt(0, 4321);
    System.out.println("Original(50): " + original.readInt(50));
    System.out.println("PBS(0): " + pbs.readInt(0));
    original.writeInt(54, 12345678);
    System.out.println("Original(54): " + original.readInt(54));
    System.out.println("PBS(4): " + pbs.readInt(4));
}

印刷

Original(0): 1234
PBS(0): 0
Original(50): 4321
PBS(0): 4321
Original(54): 12345678
PBS(4): 12345678
于 2018-10-17T07:56:38.440 回答