Console reader() and writer() methods in Java with examples
In the given tutorial, we are going to learn about reader() and writer() methods of Console class in Java.
reader() :
- Syntax :
public Reader reader()
- The java.io.Console.reader() method retrieves the unique Reader object associated with this console.
- This is a zero parameter method.
- This method returns the Reader correlated with the console.
- This method is generally used by sophisticated applications.
writer() :
- Syntax :
public PrintWriter writer()
- The java.io.Console.writer() method retrieves the unique PrintWriter object associated with this console.
- zero parameter method.
- It returns the PrintWriter associated with the console.
Program :
Let’s see a program to understand the use of reader() and writer() method :
- NOTE : System.console() returns null when running in an online IDE. Followimg program illustrates reader() and writer() methods in Console class in IO package.
package java; import java.io.*; import java.util.Scanner; public class ConsoleExample { public static void main(String[] args) { //Creating console object Console c = System.console(); if(c==null) { System.out.println("console is not available"); return; } //Creating PrintWriter PrintWriter p = c.writer(); System.out.println("PrintWriter is created"); String s = c.readLine("Enter string : "); //Creating Scanner object Scanner sc1 = new Scanner(c.reader()); while (sc1.hasNext()) { //Reading String str = sc1.next(); //Printing System.out.println(str); } } }
Output :
The output of the program will be :
Printwriter is created Enter string : Welcome here...!!! Welcome here...!!!
Also read: Valid Variants of main() in Java
Leave a Reply