Vitor Santos Vitor Santos - 1 year ago 73
Java Question

Copying part of a File to a byte array in Java

Is there any way to read part of a file to be imported into a byte array?

I would like to know how, because I can only found ways to convert the whole file into a byte array which is a very heavy memory hungry operation.

Answer Source

I'd use RandomAccessFile:

public static byte[] readFileSegment(File file, int index, int count) {
    RandomAccessFile raf = new RandomAccessFile(file);
    byte[] buffer = new byte[count];
    try {
        raf.readFully(buffer, 0, count);
        return buffer;
    } finally {

There are other alternatives with memory mapped files, NIO etc - but this should be simple.