Ilakkiya
Ilakkiya

Reputation: 107

How to read a specific number of bytes from a file into a bytes array in Java?

I would like to read 128 bytes of my file and put into a byte array to do some processing with the 128 bytes. This should iterate over the entire length of the file (i.e. everytime read the next 128 bytes and store into a bytes array and do the processing). I am currently able to read all the bytes from the file into a single byte array.

public static void main(String[] args) throws IOException {

    Path path = Paths.get("path/t/file");
    byte[] bytes = Files.readAllBytes(path);              }

Any help would be deeply appreciated.

Upvotes: 0

Views: 3077

Answers (2)

Yonatan Kahana
Yonatan Kahana

Reputation: 146

You should just use FileInputStream:

    try {
        File file = new File("file.ext");
        RandomAccessFile data = new RandomAccessFile(file, "r");

        byte[] fullBytes = new byte[(int) file.length()];
        byte[] processBytes = new byte[128];

        for (long i = 0, len = file.length() / 128; i < len; i++) {
            data.readFully(processBytes);

            // do something with the 128 bytes (processBytes).
            processBytes = ByteProcessor.process(processBytes)

            // add the processed bytes to the full bytes array
            System.arraycopy(processBytes, 0, fullBytes, processBytes.length, fullBytes.length);

        }

    } catch (IOException ex) {
        // catch exceptions.
    }

Upvotes: 1

3kings
3kings

Reputation: 838

Here is something you can do.

public void byteStuff()
    {
        File file= new File("PATHT TO FILE");
        FileInputStream input= new FileInputStream(file);

        byte[] bytes = new byte[128];

        while((input.read(bytes)) != -1)
        {
            //byte array is now filled. Do something with it.
            doSomething(bytes);
        }
    }

Upvotes: 0

Related Questions