Vitor Santos Vitor Santos - 2 months ago 6
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

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.skipBytes(index);
        raf.readFully(buffer, 0, count);
        return buffer;
    } finally {
        raf.close();
    }
}

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

Comments