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 →
Search
R4R Team
R4Rin Top Tutorials are Core Java,Hibernate ,Spring,Sturts.The content on R4R.in website is done by expert team not only with the help of books but along with the strong professional knowledge in all context like coding,designing, marketing,etc!