×

Java Programs

Java Practice

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.

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) {
    try {
      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. 			
      FI.read(b);

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

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

Output

Enter Text File Name: TH.txt
Gwalior
Bhopal
Indore
7008

Explanation

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.




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.