Program to write data into 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 console. The readLine( ) reads a single line of data. After that we have created FileWriter class object by passing filename in constructor call. At last we have closed the stream. 


class WriteIntoFile {

 public static void main(String[] args) throws IOException {

  String str;
  FileWriter outFile;
  BufferedReader br = new BufferedReader(new InputStreamReader(;
  try {
   // Create a FileWriter.
   outFile = new FileWriter("output.txt");
  } catch (IOException e) {
   System.out.println("Cannot open file.");
  System.out.println("Enter text ('stop' to quit).");
  do {
   System.out.print(": ");
   str = br.readLine();
   if(str.compareTo("stop") == 0) 
   str = str + "\r\n"; // add newline
   outFile.write(str); //Write strings to the file.
  } while(str.compareTo("stop") != 0);
C:\>java WriteIntoFile
Enter text ('stop' to quit).
: Hi I am Rahul
: How are you ?
: stop

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