有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java中的nio内存映射文件

我正在读book,它有以下几行:

A MemoryMappedBuffer directly reflects the disk file with which it is associated. If the file is structurally modified while the mapping is in effect, strange behavior can result (exact behaviors are, of course, operating system- and filesystem-dependent). A MemoryMappedBuffer has a fixed size, but the file it's mapped to is elastic. Specifically, if a file's size changes while the mapping is in effect, some or all of the buffer may become inaccessible, undefined data could be returned, or unchecked exceptions could be thrown.

因此,我的问题是:

  • 无法将文本附加到已映射的文件中。如果是,那怎么办
  • 有人能告诉我什么是内存映射文件的实际使用情况吗?如果你能提到你通过这个解决了什么具体问题,那就太好了

如果这些问题很幼稚,请容忍我。谢谢


共 (1) 个答案

  1. # 1 楼答案

    内存映射文件比常规字节缓冲版本快得多,但它会分配整个内存。例如,如果您映射4MB文件,操作系统将在文件系统上创建4MB文件,将文件映射到内存,您只需写入内存即可直接写入文件。当您确切地知道要写入多少数据时,这很方便,因为如果您写入的数据少于指定的数据数组,那么数据数组的其余部分将被零填充。此外,Windows将锁定文件(在JVM退出之前无法删除),但在Linux上并非如此

    下面是使用内存映射缓冲区附加到文件的示例,例如,只需输入要写入的文件的文件大小:

    int BUFFER_SIZE = 4 * 1024 * 1024; // 4MB
    String mainPath = "C:\\temp.txt";
    SeekableByteChannel dataFileChannel = Files.newByteChannel("C:\\temp.txt", EnumSet.of(StandardOpenOption.WRITE, StandardOpenOption.CREATE, StandardOpenOption.APPEND));
    MappedByteBuffer writeBuffer = dataFileChannel.map(FileChannel.MapMode.READ_WRITE, FILE_SIZE, BUFFER_SIZE);
    writeBuffer.write(arrayOfBytes);