Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to read data from a File using BYTE STREAM .

Java Code Example — File Handling Programs

ADVERTISEMENT

Java Program to read data from a File using BYTE STREAM .

Objective

Write a Java program to read data from a file using Byte Streams.

Algorithm / Approach

  1. Prompt the user for a filename.
  2. Inside a try block, initialize a FileInputStream.
  3. Use fin.read() to read the very first byte. It returns an integer (the ASCII value) or -1 if the file is empty.
  4. Use a while(i != -1) loop to continuously read bytes.
  5. Inside the loop, cast the integer back to a character: (char) i and print it.
  6. Read the next byte at the end of the loop.
  7. Close the stream in the finally block.
ReadFile.java
import java.util.*;
import java.io.*;
class ReadFile {
 public static void main(String[] a)
 {
  System.out.print("Enter File Name: ");
  Scanner s=new Scanner(System.in);
  String file = s.nextLine();
  FileInputStream fin;
  try {
   fin = new FileInputStream(file);
   int i = fin.read();
   while(i != -1) {
    System.out.print((char)i);
    i = fin.read();
   }
  }
  catch(Exception e) {
   System.out.println(e);
  }
  finally {
   try{
    fin.close();
   }
   catch(Exception e) {
    System.out.print(e);
   }
  }
 }
}

Expected Output

Enter File Name: Alok.txt                                       
Java Prowess is developed by Java, Android Trainer

Explanation of the Program

  • FileInputStream is the counterpart to FileOutputStream. It reads raw bytes from a file one by one.
  • The read() method is interesting: it doesn't return a byte; it returns an int. This is because a byte can be negative (in Java, bytes are signed, -128 to 127). The method needs a way to signal "End of File", which it does by returning -1. If it returned a byte, it couldn't distinguish between actual data and EOF.
  • By casting the returned integer to a char, we convert the ASCII number back into a readable letter.

Complexity

Time Complexity O(n) - Where n is the number of bytes in the file.
Space Complexity O(1)
ADVERTISEMENT