L21 - Java IO Console
L21 - Java IO Console
10-Nov-18 2
Reading Character and String
• To read a character from a BufferedReader
int read( ) throws IOException
• When read( ) 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
• To read a string from the keyboard
String readLine( ) throws IOException
10-Nov-18 3
Reading Character and String
BRRead.java
BRReadLines.java
10-Nov-18 4
Writing Console Output
• Console output is most easily accomplished with print( ) and
println( )
• System.out is an object of class PrintStream
• And PrintStream is derived from OutputStream
• And OutputStream implements the low-level method write( )
• Example:
class WriteDemo {
public static void main(String args[]) {
int b;
b = 'A';
System.out.write(b);
System.out.write('\n');
}
}
10-Nov-18 5
The Scanner Class
• Scanner class allows you to read formatted input and converts
it into its binary form
• Scanner can be used to read input from the console, a file, and
a string
• Creating a Scanner that reads the file Test.txt:
FileReader fin = new FileReader("Test.txt");
Scanner src = new Scanner(fin);
• Creating a Scanner that reads from standard input(keyboard)
Scanner conin = new Scanner(System.in);
• Creating a Scanner that reads from a string
String instr = "10 99.88 scanning is easy.";
Scanner conin = new Scanner(instr);
10-Nov-18 6
The Scanner Class
• In general, a Scanner reads tokens from the
underlying source
• To use Scanner, follow this general procedure:
• Determine if a specific type of input is available by
calling one of Scanner’s hasNextX methods
• Here X is the type of data desired (Boolean, Byte, Int, Double,
Float, Short, Long, ….. Even an entire line)
• If input is available, read it by calling one of Scanner’s
nextX methods
• Repeat the process until input is exhausted
• Close the Scanner by calling close( )
10-Nov-18 7
Scanner Example
AvgNums.java
scannerDemo.java
10-Nov-18 8
The Console Class
• The Console Class allows you to read from and
write to the console
• Most of the functionality of the Console class is
available through System.in and System.out
• Primarily a convenience class
• Simplifying some type of console interactions such as
reading strings from the console
• Console class doesn’t provide a constructor
10-Nov-18 9
The Console Class
• Obtain an object of Console class by calling the
console() in System class
static Console console()
• If console is available, then a reference to its object
will be returned
• Otherwise null is returned
• Methods defined in Console class
• readLine()
• printf()
• readPassword()
10-Nov-18 10
The Console Example
consoleDemo.java
10-Nov-18 11