Java MappedByteBuffer map from file portion for read and write

Description

Java MappedByteBuffer map from file portion for read and write



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  v a  2s. co  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);
    }
}



PreviousNext

Related