Console

java.io.Console: New Feature in Java 6

System.console() method is used for getting a unique instance of the Class Java.io.Console. Console device is associated with current Java virtual machine running. It is assumed that underlying platform is started from interactive command line. If the virtual machine is started automatically by a background job or a service, it would not have a console.

The methods on Console are readLine(), readPassword(), flush(), format(), printf(), reader() and writer().

  • Flush() forces the buffered output to be written immediately and cleared.
  • ReadLine() reads a single line of text from the console and overloaded method with parameters format and arguments returns a formatted prompt. Readline() method returns the line of input from Console not including termination characters. Null is returned if the end of the stream reached.
  • Tip
    Java.io.Console class can be instantiated using System.console() and can be invoked for reading formatted strings and formatting input.
  • Format() method writes a formatted string to console’s output based on the parameters passed on to the method. If the format string has illegal syntax, a format specifier that is incompatible with given arguments or insufficient arguments for the format or other illegal conditions, IllegalFormatException is thrown. Format string has a syntax to support fixed text and embedded format specifiers.
     
    Format specifiers support types Boolean, date, time, character, numerical, percent and line separators. Width and precision are format specifiers. Format specifiers can have explicit indexing ,relative indexing, ordinary indexing related to the position of the argument. The maximum number of arguments is limited by the maximum dimension of java array. Missing FormatArgumentException is thrown when index does not match the respective argument.

    • Character Format flags are ‘c’ and ‘C’ for ‘\u0063’ and ‘\u0043’.
    • Numeric Format flags are ‘d’, ’o’, ’x’, ’X’ for decimal integer, base eight, base sixteen and base hexadecimal numerics respectively.
      Big Integer format flags are ‘d’, ‘o’, ‘x’, ‘X’ for decimal, base eight, base sixteen and hexadecimal big integers respectively. Float flags are ‘e’, ’E’, ’g’, ’G’, ’f’, ‘a’, ‘A’ for computerized scientific notation, upper case variant of ‘e’, general scientific notation, upper case variant of ‘g’, decimal format, hexadecimal exponential form respectively.
      Big Decimal format flags are ‘e’, ’E’, ’g’, ’G’, ’f’ for computerized scientific notation, upper case variant for ‘e’, general scientific notation, upper case variant for ‘g’, decimal format respectively.
    • Date format flags are ‘t’, ‘T’ for date and time conversion, upper case variant for ‘t’ respectively. Date time conversion characters are ‘B’, ’b’, ’h’, ’A’, ’a’, ’C’, ’Y’, ’y’, ’j’, ’m’, ’d’, ‘e‘ for locale specific full month name, abbreviated month name, same as ‘b’, full name for day of the week, short name for day of the week, four digit year, year, last two digits of the year, day of year, month, day of month with leading zeros as necessary, day of month respectively.
    • Time format flags are ‘H’, ‘I’, ‘k’, ’l’, ’M’, ’S’, ’L’, ’N’, ’p’, ’z’, ’Z’, ’s’, ’Q’ for 24 hour clock hour format, 12 hour clock hour format, hour of the day in 24 hour clock, hour for 12 hour clock, minute with in the hour, seconds within the minute, millisecond within the second format, nanosecond within the second, locale specific morning or afternoon, numeric time zone offset, time zone abbreviation, seconds since the beginning of epoch, milliseconds since the beginning of the epoch respectively.
  • Printf() is the method to write a formatted string to the output console stream. The Printf() method has specified format string and arguments. Passing arguments with format string behaves similar to format() method of Console. Illegal Format Exception is thrown if there are errors in the format string.
  • ReadPassword() returns the formatted prompt after reading the password or pass phrase from the console. An I/O Error is thrown, if there is an input error for password.
  • Reader() returns the unique Reader object for the console’s input stream. Scanner class is used for utilizing and parsing the Reader stream.
  • Writer() method returns the unique PrintWriter Object related to Console object.

1. Project Structure

Eclipse Project
Eclipse Project

JavaCodeGeeksConsole.java

package com.javacodegeeks.io;

import java.io.Console;
import java.io.PrintWriter;
import java.util.Scanner;

/**
 * @author Bhagvan Kommadi
 * Console Example for virtual machine console input and output
 */
public class JavaCodeGeeksConsole {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		
		Console console = System.console();
		
		String user = console.readLine("UserName: ");
		
		char[] password = console.readPassword("Password: ");
		
		System.out.println("Username: "+ user);
		
		System.out.println("Password: "+ password);
		
		console.flush();
		
		String formattedString = "%1$1s %2$2s %3$4s%n";
		
		console.printf(formattedString, "input11","input12","input13");
		console.printf(formattedString, "input21","input22","input23");
		console.printf(formattedString, "input31","input32","input33");
		console.printf(formattedString, "input41","input42","input43");
		
		System.out.println("");
		
		Scanner scanner = new Scanner(console.reader());
		
		int intValue=0;
		
		   console.printf("input a integer between 0 and 99 \n");
		   
		   intValue = scanner.nextInt();
		
		System.out.println("inputted integer Value " +intValue);
		
		PrintWriter printWriter = console.writer();
		
		printWriter.println("printing into console output");
		
		

	}

}

2. Demo

Console Sample
Console Sample

3. Closing Words

Console has support for reading strings with format, passwords and methods for inputstream and outputstream access.

4. Download the Eclipse Project

Download
You can download the eclipse project of this example here: JavaCodeGeeksConsole

Bhagvan Kommadi

Bhagvan Kommadi is the Founder of Architect Corner & has around 20 years’ experience in the industry, ranging from large scale enterprise development to helping incubate software product start-ups. He has done Masters in Industrial Systems Engineering at Georgia Institute of Technology (1997) and Bachelors in Aerospace Engineering from Indian Institute of Technology, Madras (1993). He is member of IFX forum,Oracle JCP and participant in Java Community Process. He founded Quantica Computacao, the first quantum computing startup in India. Markets and Markets have positioned Quantica Computacao in ‘Emerging Companies’ section of Quantum Computing quadrants. Bhagvan has engineered and developed simulators and tools in the area of quantum technology using IBM Q, Microsoft Q# and Google QScript. He has reviewed the Manning book titled : "Machine Learning with TensorFlow”. He is also the author of Packt Publishing book - "Hands-On Data Structures and Algorithms with Go".He is member of IFX forum,Oracle JCP and participant in Java Community Process. He is member of the MIT Technology Review Global Panel.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button