Java File Read via ByteBuffer openReadOnly(Path path, int offset, int length)

Here you can find the source of openReadOnly(Path path, int offset, int length)

Description

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

License

Open Source License

Parameter

Parameter Description
path a parameter
offset a parameter
length a parameter

Exception

Parameter Description
IOException an exception

Declaration

public static MappedByteBuffer openReadOnly(Path path, int offset, int length) throws IOException 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

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   ww w .  ja v  a2s. 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);
    }
}

Related

  1. getReadBuffer(File file)
  2. getStringContents(ReadableByteChannel channel)
  3. largeFileReader(String filename)
  4. mapReadWrite(File file)
  5. nioCopy(ReadableByteChannel input, WritableByteChannel output)
  6. read(DataInput in, int length)
  7. read(File file)
  8. read(File file)
  9. read(File file, long offset, int length)