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:

  1. import java.io.*;
  2. public class KeyboardInput
  3. {
  4. public static void main(String args[])
  5. {
  6. String s;
  7. // create a buffered reader to read each line from the keyboard.
  8. InputStreamReader ir = new InputStreamReader(System.in);
  9. BufferedReader in = new BufferedReader(ir);
  10. System.out.println(“Unix: Type ctrl-d to exit.” + “\nWindows: Type ctrl-z to exit”);
  11. try{
  12. // read each input line and echo it
  13. s = in.readLine();
  14. while ( s!= null )
  15. {
  16. System.out.println(“Read: ”+s);
  17. s = in.readLine();
  18. // close the buffered reader.
  19. in.close();
  20. }
  21. }catch(IOException e)
  22. {
  23. // catch any exceptions.
  24. e.printStackTrace();
  25. }
  26. }
  27. }

  • 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.

Console I/O in JAVA

  • 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:

  1. import java.io.*;
  2. import java.util.Scanner;
  3. public class ScannTest
  4. {
  5. public static void main(String args[])
  6. {
  7. Scanner s = new Scanner(System.in);
  8. String param = s.next();
  9. System.out.println(“the param 1” + param);
  10. int value = s.nextInt();
  11. System.out.println(“second param” + value);
  12. s.close();
  13. }
  14. }

  • 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.

Written by Sourabh Bhunje

Sourabh Bhunje, B.E. IT from Pune University. Currently Working at Techliebe. Professional Skills: Programming - Software & Mobile, Web & Graphic Design, Localization, Content Writing, Sub-Titling etc. http://techliebe.com/about-us

Leave a Comment