# java使用mmap

文件操作，可以通过mmap将文件映射到内存，提升写入性能

```java
public class MmapMain {

    private static final int FILE_SIZE = 1 << 22;

    public static void main(String[] args) throws IOException {
        long begin = System.currentTimeMillis();
        random();
        long end = System.currentTimeMillis();
        System.out.println("random cost=" + (end - begin));

        begin = System.currentTimeMillis();
        stream();
        end = System.currentTimeMillis();
        System.out.println("stream cost=" + (end - begin));

        begin = System.currentTimeMillis();
        mmap();
        end = System.currentTimeMillis();
        System.out.println("mmap cost=" + (end - begin));
    }


    private static void random() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("random.txt", "rw");
        byte[] bytes = new byte[1];
        bytes[0] = (byte) 'a';
        for (int i = 0; i < FILE_SIZE; i++) {
            raf.write(bytes);
        }
    }

    private static void stream() throws IOException {
        byte[] bytes = new byte[1];
        try (FileOutputStream outputStream = new FileOutputStream("stream.txt")) {
            bytes[0] = (byte) 'a';
            for (int i = 0; i < FILE_SIZE; i++) {
                outputStream.write(bytes);
            }
        }
    }

    private static void mmap() throws IOException {
        RandomAccessFile raf = new RandomAccessFile("mmap.txt", "rw");
        MappedByteBuffer mbb = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, FILE_SIZE);
        byte bt = (byte) 'a';
        for (int i = 0; i < FILE_SIZE; i++) {
            mbb.put(bt);
        }
    }
}
```

执行日志如下

```
random cost=16955
stream cost=16085
mmap cost=18
```

可以看出，在4M文件顺序写入的情况下，mmap性能比其他模式高出好几个数量级


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://kennethfan.gitbook.io/notes/java-study/java-shi-yong-mmap.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
