Console I/O in Java
Console I/O:-
- Most application must interact with the user. Such interaction is sometimes accomplished with text input and output to the console (using the keyboard as the standard input and using the terminal window as the standard output).
Java JDK supports console I/O with three public static variables on the java.lang.System class:
- The variable System.out is a PrintStream object that refers (initially) to the terminal window that launched the Java technology application.
- The variable System.in is an InputStream object that refers (initially) to the user’s keyboard.
- The variable System.err is a PrintStream object that refers (initially) to the terminal window that launched the Java technology application.
It is possible to reroute these streams using the static methods:
System.setOut, System.setIn, and System.setErr.
For example, you could reroute standard error to a file stream.
Writing to Standard Output:-
- You can write standard output through the System.out.println(String) method.
- This PrintStream method prints the string argument to the console and adds a newline character at the ens.
- The following methods are also supported to print other types: primitive, a character buffer, and an arbitrary object.
- All of those methods add a newline character at the end of the output.
void println(boolean)
void println(char)
void println(double)
void println(float)
void println(int)
void println(long)
void println(char[])
void println(Object)
- There is also a corresponding set of overloaded methods, called print, that do not add the newline character.
Reading from Standard Input:-
- The example given below shows a technique that you should use to read String information from the console standard input:
- import java.io.*;
- public class KeyboardInput
- {
- public static void main(String args[])
- {
- String s;
- // create a buffered reader to read each line from the keyboard.
- InputStreamReader ir = new InputStreamReader(System.in);
- BufferedReader in = new BufferedReader(ir);
- System.out.println(“Unix: Type ctrl-d to exit.” + “\nWindows: Type ctrl-z to exit”);
- try{
- // read each input line and echo it
- s = in.readLine();
- while ( s!= null )
- {
- System.out.println(“Read: ”+s);
- s = in.readLine();
- // close the buffered reader.
- in.close();
- }
- }catch(IOException e)
- {
- // catch any exceptions.
- e.printStackTrace();
- }
- }
- }
- Line 8 declares a String variable, s that the program uses to hold each line read from standard input.
- Line 10 and Line 11 wrap System.in with two support object that message the stream of bytes coming from standard input.
- The InputStreamReader(ir) reads character and converts the raw bytes into Unicode characters.
- The BufferedReader(in) provides the readLine method which enables the program to read from standard input one line at a time.
Note: – the Control-d character on the UNIX platform indicates the end of file condition. In the Microsoft windows environment, use the keystroke sequence Control-z by pressing the Enter key to indicate end of file EOF.
- Line 16 reads the first line of text from standard input. The while loop (Line 18 – Line 24) iteratively prints out the current line and reads the next line.
- This code could be rewritten more succinctly (but more cryptically) as:
while((s = in.readLine()) != null)
{
System.out.println(“Read: ”+s);
}
- Because the readLine method can throw an I/O exception, you must wrap all of this code in a try catch block.
- Line 23 closes the outer most input stream to release any system resources related to creating these stream objects.
- Finally, the program handles any I/O exceptions that might occur.
Note: – the call to the close method on Line 23 should really be performed in a finally clause. This is not done in this code example for reasons of brevity.
Simple Formatted Output:-
- In java programming language version 5 provided C language style printf functionality.
- It provides standard formatted output from the program. This enables programmers to migrate from legacy code.
- You can use the printf as normal C and C++ syntax.
System.out.printf(“%s%5d%f%n”,name,id,salary);
- This formatting functionality is also available in the String class in the format method.the same output can also be generated as follows:
String s = String.format(“%s%5d%f%n”,name,id,salary);
System.out.print(s);
The given below shows a few common formatting codes.
Code Description
%s Formats the argument as a string, usually by calling the toString method on the object
%d %o %x formats an integer, as a decimal, octal, or hexadecimal value.
%f %g formats a floating point number. The %g code uses scientific notation.
%n inserts a newline character to the string or stream.
%% insert the % character to the string or stream.
- You can use %n for the newline character, instead of \n, for platform independence.
Note: – For more information about the functionality of printf and the formatting codes, read the API document for the class java.util.Formatter.
Simple Formatted Input:-
- The Scanner class provides formatted input functionality. It s part of the java.util package. It provides methods for getting primitive values and strings and blocks as it waits for input from the user.
- An example is shown below:
- import java.io.*;
- import java.util.Scanner;
- public class ScannTest
- {
- public static void main(String args[])
- {
- Scanner s = new Scanner(System.in);
- String param = s.next();
- System.out.println(“the param 1” + param);
- int value = s.nextInt();
- System.out.println(“second param” + value);
- s.close();
- }
- }
- In the given code, Line 9 creates a Scanner reference by passing directly the console input.
- Line 10 retrieves the string value from the given input by using the Scanner method next.
- Line 12 gets the integer value of the given input by using the nextInt method.
- Line 14 closes the input from the user.
Note: – Scanner class can be used to break down the formatted input into different tokens of primitive and String types. You can also use regular expressions to scan streams.