Menu
Topics Index
...
`


Input/Output: Exploring java.io >
Siva Nookala - 15 Apr 2016
Console is a class in Java which is having methods that help in reading text from Console or writing text to console.

Methods of Console Class :
Method Description
Reader reader() Retrieves the unique Reader object associated with this console.
String readLine() Reads a single line of text from the console.
char[] readPassword() Reads a password or passphrase from the console with echoing disabled
PrintWriter writer() Retrieves the unique PrintWriter object associated with this console.
Console printf(String format, Object... args) A convenience method to write a formatted string to this console's output stream using the specified format string and arguments.
void flush() Flushes the console and forces any buffered output to be written immediately .
Console format(String fmt, Object... args) Writes a formatted string to this console's output stream using the specified format string and arguments.
Example Programs :
Note : Compile & Execute the above program from Command Prompt. To see the output.
import java.io.*;
import java.util.Scanner;
class ConsoleReader
{
    public static void main(String args[])
    {    
        Console console = System.console();
        System.out.print("Enter Input : " );
        Scanner scr = new Scanner(console.reader()); // Assigning reader to scanner
        
        while(scr.hasNext())
        {
            System.out.println(scr.next()+ " ");
        }
    }
}
Enter Input : Hello Merit Campus
Hello
Merit
Campus
import java.io.*;
class ConsoleWriter
{
    public static void main(String args[])
    {
        Console console = System.console();
        PrintWriter writer = console.writer();
        String s = "Hello MeritCampus";
        writer.write(s); // writing string to writer
        writer.println(); // Printing from writer
    }
}
Hello MeritCampus
public class ConsoleDemo
{
    public static void main(String args[])
    {
        Console console = System.console();
        String userName = console.readLine("Enter Username :");
        char[] password = console.readPassword("Enter Password :");
        System.out.println("Welcome " + userName);
        System.out.println("Your password is : "+ new String(password));
    }
}
Enter Username : Admin
Enter Password :
Welcome Admin
Your password is : 1234

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.