Sunday, 26 January 2014

READING CONSOLE INPUT

READ INPUT FROM  CONSOLE-JAVA

How to Read Input From Console in java

Reading console input in simple java console applications is a very straight forward process. Java provides developers two predefined streams in the java.lang.System class to read and write data to and from standard input and output devices. System.out is a standard output stream which is Console by default and System.in is predefined input stream which is Keyboard by default. To read user input in a console window we connect system.in with other stream classes available in java.io package.



In Java, console input is accomplished by reading from System.in. To obtaina character-based stream that is attached to the console, you wrap System.in in a BufferedReader object, to create a character stream. BuffereredReader supports abuffered input stream. Its most commonly used constructor is shown here:


                                       BufferedReader(ReaderinputReader)

The inputReaderis the stream that is linked to the instance of BufferedReader that is being created. Readeris an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters. To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

                                  InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

                             BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

READING CHARACTERS:


To read a character from a BufferedReader, use read( ). The version ofread( ) that we will be using is

                             int read( ) throws IOException

Each time thatread( ) is called, it reads a character from the input stream and returns it as an integer value. It returns -1 when the end of the stream is encountered. As you can see, it can throw an IOException.

READING STRING:


To read a string from the keyboard, use the version ofreadLine( ) that is a member of the BufferedReader class. Its general form is shown here:

String readLine( ) throws IOException

Example:
// Use a BufferedReader to read characters from the console.
import java.io.*;
class BRRead {
public static void main(String args[])
throws IOException{
char c;
BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter characters, 'q' to quit.");
do
{
c = (char) br.read();
System.out.println(c);

while(c != 'q');
}
}


OUTPUT:

Enter characters, 'q' to quit.
123abcq
1
2
3
a
b
c
q





:




No comments:

Post a Comment