Home » Java programs » DataInputStream programs

Java program to read an array using ByteStream

In this java program, we are going to learn how to read an array using ByteStream? ByteStream reads and write byte by byte data from/in a file.

Given an array and we have to read it byte-by-byte using ByteStream.


A ByteStream is a key to access or to read the file "byte-by-byte". ByteStream reads and write a byte at a time, this needs a lower level of machine resources. In java there are number of ByteStream classes like InputStream and OutputStream.

Consider the program:

import java.io.FileInputStream;
import java.io.IOException;
import java.util.Scanner;

public class ReadBytes 
	public static void main(String[] args) 
			Scanner KB=new Scanner(System.in);
			// KB is the object of Scanner class which takes the input. 

			System.out.print("Enter Text File Name:");
			// Write Name of the file wants to read. 			
			String filename=KB.next();

			FileInputStream FI=new FileInputStream(filename);			
			byte b[]=new byte[FI.available()];

			// b is the object of the byte stream. 			

			// here .read function will read the bytestream byte-by-byte. 			
			String c=new String(b);

			// read and print the file data on the output screen. 			
			// .close function will close the current file which is open. 
		catch(IOException e)
		// If an error occurs in the program. 
			// Print the line or tell where the error occurs in the program. 


Enter Text File Name: TH.txt


In this program, we are reading a file with the help of ByteStream. So we have to input a file name which is to be read, when we enter the name we have to check that the file is present there or not, if the file is already being present there then we can easily read the file byte-by-byte and display on the screen.

Was this page helpful? YES NO

Are you a blogger? Join our Blogging forum.

Comments and Discussions

We are using Google to publish ads on our website; Google has its own privacy policies. They may save log, cookies on your system. Google may also collect information of your system like IP address, region, city, country. For more details please go through the Google’s privacy policy.