Tuesday, 29 November 2016

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. 

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;

class WriteIntoFile {

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

  String str;
  FileWriter outFile;
  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
  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:\>javac WriteIntoFile.java
C:\>java WriteIntoFile
Enter text ('stop' to quit).
: Hi I am Rahul
: How are you ?
: stop

No comments:

Post a comment