Java File Read via ByteBuffer read(File file, long offset, int length)

Here you can find the source of read(File file, long offset, int length)

Description

read

License

Apache License

Declaration

public static ByteBuffer read(File file, long offset, int length) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;

import java.io.IOException;

import java.io.RandomAccessFile;

import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class Main {
    public static ByteBuffer read(File file, long offset, int length) throws IOException {
        FileChannel chan = channel(file, false);

        ByteBuffer buf = ByteBuffer.allocate(length);
        chan.position(offset);/*from w  w  w  .j a v a 2s . c o  m*/

        while (buf.remaining() > 0) {
            if (chan.read(buf) <= 0) {
                throw new IOException("Failed to read from channel.");
            }
        }

        buf.rewind();
        chan.close();

        return buf;
    }

    public static FileChannel channel(File file, boolean writeable) throws IOException {
        String opts = writeable ? "rw" : "r";
        RandomAccessFile fd = new RandomAccessFile(file, opts);
        FileChannel chan = fd.getChannel();

        return chan;
    }
}

Related

  1. nioCopy(ReadableByteChannel input, WritableByteChannel output)
  2. openReadOnly(Path path, int offset, int length)
  3. read(DataInput in, int length)
  4. read(File file)
  5. read(File file)
  6. read(File from)
  7. read(final File source)
  8. read(final FileChannel channel)
  9. read(final Reader input, final char[] buffer, final int offset, final int length)