Read file into byte array example

This example shows you to read the file into byte array in java.

Below is the example code:

package com.java.connect.io;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

//Read file into byte array example
public class ReadFileIntoByteArrayExample {
	public static void main(String[] args) throws IOException {
		// Get the file object
		File file = new File("test.txt");
		// Get the input stream by passing file
		InputStream inputStream = new FileInputStream(file);

		int offset = 0;
		int bytesRead;
		// Get the byte array
		byte[] bytes = new byte[(int) file.length()];
		// Iterate the byte array
		while (offset < bytes.length
				&& (bytesRead = inputStream.read(bytes, offset, bytes.length
						- offset)) >= 0) {
			offset += bytesRead;
		}
		// Close after use
		inputStream.close();
	}
}