Program to read the contents of file using Character Stream

Character Streams are specially designed to read and write data from and to the Streams of Characters. We require this specialized Stream because of different file encoding systems. We should not use Byte Streams for Reading and Writing character files. In Character Streams all the classes are the descendents of 2 abstract classes:
  1. Reader for reading operation.
  2. Writer for writing operation.

The 2 most important methods in all the classes that are used for I/O operations are:
  1. public int read( ) throws IOException : It reads a character from stream.
  2. public int write(int i) throws IOException : It writes the Character into the Stream. Data into 16 lower bits are converted into characters and higher 16 bits are ignored..
Here we have used BufferedReader to read the a line of data from file which takes FileReader object as an argument. The readLine( ) reads a single line of data. After reading data we close the stream using void close( ) method of FileReader.


PROGRAM
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;

class ReadFromFile {

 public static void main(String[] args) throws Exception {
  
  FileReader inFile = new FileReader(args[0]);
  BufferedReader br = new BufferedReader(inFile);
  
  String s;
  
  System.out.println("The contents of " + args[0] + "file are....");
  /* Read lines from the file and display them on the screen. */
  while((s = br.readLine()) != null) {
   
   System.out.println(s);
  }
  inFile.close();
 }
}
OUTPUT
C:\>javac ReadFromFile.java
C:\>java ReadFromFile test.txt
The contents of test.txtfile are....
Hi
This is printing from
file 'text.txt'.

Popular posts from this blog

Program to define a class 'employee' with data members as empid, name and salary. Accept data for 5 objects using Array of objects and print it.

Define a class Student with four data members such as name, roll no.,sub1, and sub2. Define appropriate methods to initialize and display the values of data members. Also calculate total marks and percentage scored by student.

Program to input age from user and throw user-defined exception if entered age is negative