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
- Prompt the user for a filename.
- Inside a
tryblock, initialize aFileReader. - Use
freader.read()to read the first character (returned as an integer). - Use a
while(i != -1)loop to read through the file. - Cast the integer to a
charand print it. - Close the reader in the
finallyblock.
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
FileReaderworks almost identically toFileInputStreamin terms of the code structure.- The key difference happens under the hood:
FileReaderreads 16-bit Unicode characters, ensuring that international text and special symbols are decoded correctly, whereasFileInputStreamreads raw 8-bit bytes which might corrupt multi-byte characters.
Complexity
Time Complexity
O(n)
Space Complexity
O(1)