Example & Tutorial understanding programming in easy ways.

How to read file content using byte array in java?.

In this example shows you how to read a binary file into byte array from Java program. This type of example code is need where you have to read the binary data into byte array and use the byte array data for further processing.

To the binary file into byte array we will use the class InputStream of java.io package. This class is providing read() method with reads the data into byte stream.

Following line of code can be used:

insputStream.read(bytes);

Example: the Java program that reads the binary file into byte array:

package javatest;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

/**

* Reading contents from a file into byte array.

public class FileToByteArray {

public static void main(String a[]){

String fileName = "C:/MyFile.txt";

InputStream is = null;

try {

is = new FileInputStream(fileName);

byte content[] = new byte[2*1024];

int readCount = 0;

while((readCount = is.read(content)) > 0){

System.out.println(new String(content, 0, readCount-1));

}

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

try{

if(is != null) is.close();

} catch(Exception ex){

}}}}

Read More →