我已经为要用作不同Java进程之间的共享缓存的文件创建了MappedBytes
实例。
我希望能够从原始文件中分离出其他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
副本已修改,但不是原始副本。我想修改原始文件,可以按字节记录吗?
感谢您的帮助, 乔什。
答案 0 :(得分: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