Skip to main content

ProwessApps

Learn · Practice · Excel

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

Java Code Example — File Handling Programs

ADVERTISEMENT

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

Objective

Write a Java program to read text from a file using Character Streams.

Algorithm / Approach

  1. Prompt the user for a filename.
  2. Inside a try block, initialize a FileReader.
  3. Use freader.read() to read the first character (returned as an integer).
  4. Use a while(i != -1) loop to read through the file.
  5. Cast the integer to a char and print it.
  6. Close the reader 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 fileName = s.nextLine();
  FileReader freader = null;
  try {
   freader = new FileReader(fileName);
   int i = freader.read();
   while(i != -1) {
    System.out.print((char)i);
    i = freader.read();
   }
  }
  catch(Exception e) {
   System.out.println(e);
  }
  finally {
   try{
    freader.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

  • FileReader works almost identically to FileInputStream in terms of the code structure.
  • The key difference happens under the hood: FileReader reads 16-bit Unicode characters, ensuring that international text and special symbols are decoded correctly, whereas FileInputStream reads raw 8-bit bytes which might corrupt multi-byte characters.

Complexity

Time Complexity O(n)
Space Complexity O(1)
ADVERTISEMENT