e166. creating a memory-mapped file.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 20 行

TXT
20
字号
Mapping a file in memory results in a ByteArray object. To access the byte array, see e159 Getting Bytes from a ByteBuffer and e160 Putting Bytes into a ByteBuffer. 
    try {
        File file = new File("filename");
    
        // Create a read-only memory-mapped file
        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
        ByteBuffer roBuf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
    
        // Create a read-write memory-mapped file
        FileChannel rwChannel = new RandomAccessFile(file, "rw").getChannel();
        ByteBuffer wrBuf = rwChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int)rwChannel.size());
    
        // Create a private (copy-on-write) memory-mapped file.
        // Any write to this channel results in a private copy of the data.
        FileChannel pvChannel = new RandomAccessFile(file, "rw").getChannel();
        ByteBuffer pvBuf = roChannel.map(FileChannel.MapMode.READ_WRITE, 0, (int)rwChannel.size());
    } catch (IOException e) {
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?