AdSense

AdSense3

Sunday, 9 November 2014

Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop

Reading data from keyboard:

There are many ways to read data from the keyboard. For example:
  • InputStreamReader
  • Console
  • Scanner
  • DataInputStream etc.

InputStreamReader class:

InputStreamReader class can be used to read data from keyboard.It performs two tasks:
  • connects to input stream of keyboard
  • converts the byte-oriented stream into character-oriented stream

BufferedReader class:

BufferedReader class can be used to read data line by line by readLine() method.

Example of reading data from keyboard by InputStreamReader and BufferdReader class:

In this example, we are connecting the BufferedReader stream with the InputStreamReader stream for reading the line by line data from the keyboard.
  1. //<b><i>Program of reading data</i></b>  
  2.   
  3. import java.io.*;  
  4. class G5{  
  5. public static void main(String args[])throws Exception{  
  6.   
  7. InputStreamReader r=new InputStreamReader(System.in);  
  8. BufferedReader br=new BufferedReader(r);  
  9.   
  10. System.out.println("Enter your name");  
  11. String name=br.readLine();  
  12. System.out.println("Welcome "+name);  
  13.  }  
  14. }  
Output:Enter your name
       Amit
       Welcome Amit
keyboard

In this example, we are reading and printing the data until the user prints stop.

  1. import java.io.*;  
  2. class G5{  
  3. public static void main(String args[])throws Exception{  
  4.   
  5.  InputStreamReader r=new InputStreamReader(System.in);  
  6.  BufferedReader br=new BufferedReader(r);  
  7.   
  8.  String name="";  
  9.   
  10.   while(name.equals("stop")){  
  11.    System.out.println("Enter data: ");  
  12.    name=br.readLine();  
  13.    System.out.println("data is: "+name);  
  14.   }  
  15.   
  16.  br.close();  
  17.  r.close();  
  18.  }  
  19. }  
Output:Enter data: Amit
       data is: Amit
       Enter data: 10
       data is: 10
       Enter data: stop
       data is: stop

No comments:

Post a Comment