Java examples for java.nio:ByteBuffer Read
Maps a portion of a file to memory and returns the mapped read-only byte buffer using the given offset and length.
//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 { /**//from w w w.ja va 2 s . c o m * Maps a portion of a file to memory and returns the mapped read-only byte * buffer using the given offset and length. * * @param path * @param offset * @param length * @return * @throws IOException */ public static MappedByteBuffer openReadOnly(Path path, int offset, int length) throws IOException { try (FileChannel fc = FileChannel.open(path, READ)) { return fc.map(READ_ONLY, offset, truncateLength(fc, length)); } } /** * Maps the whole file to memory and returns the mapped read-only byte buffer. * If the file is larger than {@link java.lang.Integer#MAX_VALUE}, then all * bytes beyond that limit are omitted. * * @param path * @return * @throws IOException */ public static MappedByteBuffer openReadOnly(Path path) throws IOException { return openReadOnly(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); } }