Java.io - SPLessons

Java.io Console

Chapter 10

SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

Java.io Console

Java.io Console

shape Introduction

The Java.io Console is the class used to access the input from the console. The methods which are available in console class are used to read the data like password, text. By using the console class for reading password then it is not visible to the user the console class will hide it.

Class Declaration

shape Declaration

Java.io Console class is declared below:
Public final class console extends object  implements Flushable

Class Methods

shape Table

Method Description
void flush () The function of this method is to flush the specified output stream.
String readLine() The function of this method is to read the content of text from console.
char[] readPassword The function of this method is to read the content related to password which is not displayed on console.
console printf(String format, Object  args) The function of this method is to write the content the string format to the output stream.

Inherited Methods

shape Description

From the following classes, methods are inherited to console class.

  • Java.io.Object

shape Examples

Usage of Printwriter writer() method.

import java.io.Console;
import java.io.PrintWriter;
public class Console 
{
   public static void main(String[] args) 
   {
      
      Console cnsl = null;
      PrintWriter out = null;
      
      try{
         // creating a console object
         cnsl = System.console();

         // If console is not null then
         if (cnsl != null) {
            
            // creating a new print writer
            out = cnsl.writer();
            
            // print
            out.println("SP LESSONS");
         }      
      }catch(Exception ex)
      {
         
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

Output
The result will be as follows.

SP LESSONS

Usage of char[] readPassword ()method.

import java.io.Console;
public class Console  
{
	
	//class Splesson{  
	public static void main(String args[])
	{  
	Console c=System.console();  
	System.out.println("Enter password: ");  
	char[] ch=c.readPassword();  
	String pass=String.valueOf(ch);//converting char array to string  
	System.out.println("Password is: "+pass);  
	}  
	}

Output
When enter the password result will be as follows.

Enter password:
Password is:splessons

Summary

shape Key Points

  • The Java.io Console is the class used to access the input from the console.
  • The methods which are available in console class are used to read the data like password, text.
  • By using the Java.io Console class for reading password then it is not visible to the user the console class will hide it.