Vitor Santos Vitor Santos - 10 months ago 52
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.


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.