C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

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.