Maps a portion of a file to memory and returns the mapped writable byte buffer using the given offset and length. - Java java.nio

Java examples for java.nio:ByteBuffer File

Description

Maps a portion of a file to memory and returns the mapped writable byte buffer using the given offset and length.

Demo Code


//package com.java2s;
import java.io.IOException;

import java.nio.MappedByteBuffer;

import java.nio.channels.FileChannel;
import static java.nio.channels.FileChannel.MapMode.*;
import java.nio.file.Path;
import static java.nio.file.StandardOpenOption.*;

public class Main {
    /**//  w w  w.  j  a  va 2  s. c o  m
     * Maps a portion of a file to memory and returns the mapped writable byte
     * buffer using the given offset and length. If the file doesn't exist, it
     * will be created.
     * 
     * @param path
     * @param offset
     * @param length
     * @return
     * @throws IOException 
     */
    public static MappedByteBuffer openReadWrite(Path path, int offset,
            int length) throws IOException {
        try (FileChannel fc = FileChannel.open(path, READ, WRITE, CREATE)) {
            return fc.map(READ_WRITE, offset, truncateLength(fc, length));
        }
    }

    /**
     * Maps the whole file to memory and returns the mapped writable byte buffer.
     * If the file is larger than {@link java.lang.Integer#MAX_VALUE}, then all
     * bytes beyond that limit are omitted. If the file doesn't exist, it will be
     * created.
     * 
     * @param path
     * @return
     * @throws IOException 
     */
    public static MappedByteBuffer openReadWrite(Path path)
            throws IOException {
        return openReadWrite(path, 0, -1);
    }

    private static int truncateLength(FileChannel fc, int length)
            throws IOException {
        return (int) Math.min(length > 0 ? length : fc.size(),
                Integer.MAX_VALUE);
    }
}

Related Tutorials