Java.io.Console.reader() 方法



描述

java.io.Console.reader() 方法检索与该控制台关联的唯一 Reader 对象。

声明

以下是 java.io.Console.reader() 方法的声明:

public Reader reader()

参数

返回值

此方法返回与控制台关联的读取器。

异常

示例

以下示例演示了 java.io.Console.reader() 方法的使用。

package com.tutorialspoint;

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

public class ConsoleDemo {
   public static void main(String[] args) {      
      Console cnsl = null;
      Scanner scan = null;
      
      try {
         // creates a console object
         cnsl = System.console();

         // if console is not null
         if (cnsl != null) {
            
            // prints
            System.out.print("Enter name : ");
            
            // create new scanner object
            scan = new Scanner(cnsl.reader());
            
            // read till the end of data
            while (scan.hasNext()) {
               
               // read next
               String str = scan.next();
               
               // print
               System.out.println(str);
            }
         }      
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

让我们编译并运行上述程序,这将产生以下结果:

Enter name : Master Programmer
Master Programmer
java_io_console.htm
广告

© . All rights reserved.