Java.io.Console.readPassword() 方法



描述

java.io.Console.readPassword(String fmt, Object... args) 方法提供一個格式化的提示,然後讀取控制檯上的密碼,並停用回顯。

宣告

以下是 java.io.Console.readPassword(String fmt, Object... args) 方法的宣告:

public char[] readPassword(String fmt, Object... args)

引數

  • fmt − 用於提示文字的格式字串,如格式字串語法中所述。

  • args − 格式字串中格式說明符引用的引數。

返回值

此方法返回一個包含從控制檯讀取的密碼的字元陣列,不包括行終止字元,如果已到達檔案末尾則返回 null。

異常

  • IllegalFormatException − 如果格式字串包含非法的語法、與給定引數不相容的格式說明符、給定格式字串的引數不足或其他非法條件。

  • IOError − 如果發生 I/O 錯誤。

示例

以下示例演示了 java.io.Console.readPassword(String fmt, Object... args) 方法的使用。

package com.tutorialspoint;

import java.io.Console;

public class ConsoleDemo {
   public static void main(String[] args) {      
      Console cnsl = null;
      String alpha = null;
      String fmt = "%2$5s %3$10s%n";
      
      try {
         // creates a console object
         cnsl = System.console();

         // if console is not null
         if (cnsl != null) {
            
            // read line from the user input
            alpha = cnsl.readLine(fmt,"Your","Name: ");
            
            // prints
            System.out.println("Name is: " + alpha);
            
            // read password into the char array
            char[] pwd = cnsl.readPassword(fmt,"Enter","Password: ");
            
            // prints
            System.out.println("Password is: "+pwd);
         }    
         
      } catch(Exception ex) {
         // if any error occurs
         ex.printStackTrace();      
      }
   }
}

讓我們編譯並執行上述程式,這將產生以下結果:

Your Name: Master Programmer
Name is: Master Programmer
Enter Password: 
Password is: Good Morning
java_io_console.htm
廣告