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.
|
//Program of reading data
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
System.out.println("Enter ur name");
String name=br.readLine();
System.out.println("Welcome "+name);
}
}
Output:Enter ur name
Amit
Welcome Amit
Another Example of reading data from keyboard by InputStreamReader and BufferdReader class until the user writes stop
| In this example, we are reading and printing the data until the user prints stop.
|
import java.io.*;
class G5{
public static void main(String args[])throws Exception{
InputStreamReader r=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(r);
String name="";
while(name.equals("stop")){
System.out.println("Enter data: ");
name=br.readLine();
System.out.println("data is: "+name);
}
br.close();
r.close();
}
}
Output:Enter data: Amit
data is: Amit
Enter data: 10
data is: 10
Enter data: stop
data is: stop
|