MappedByteBuffer 写文件

MappedByteBuffer中“put”和“force”的区别是什么

 

 put()将数据存储在缓冲区中,force()通知操作系统将缓冲区刷新到磁盘。

put() 后,打开文件,也能看到文件中有数据,这是因为没有绕过操作系统,看到的是操作系统文件缓存里的内容,不是磁盘上的内容

可以断电或通过U盘写入,插拔来验证

@Test
public void MappedByteBufferTest() throws Exception {
    int count = 10;
    RandomAccessFile memoryMappedFile = new RandomAccessFile("D:\\1.txt", "rw");

    MappedByteBuffer out = memoryMappedFile.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, count);

    for (int i = 0; i < count; i++) {
        out.put((byte) i);
    }
    out.force();
    memoryMappedFile.close();
}

 

posted @ 2022-08-01 08:58  VipSoft  阅读(288)  评论(0编辑  收藏  举报