Java – 读取控制台输入

这是一个快速参考代码示例,可使用 Java IO 从控制台读取输入。 这主要是为我的初学者准备的,因此,如果您已经知道它,请随时跳过。

Table of contents

1) Read console input using java.io.Console instance
2) Read console input using BufferedReader instance
3) Read console input using Scanner instance

让我们直接跳至示例代码。

1)使用java.io.Console实例读取控制台输入

private static void usingConsoleReader()
{
  Console console = null;
  String inputString = null;
  try
  {
	 // creates a console object
	 console = System.console();
	 // if console is not null
	 if (console != null)
	 {
		// read line from the user input
		inputString = console.readLine("Name: ");
		// prints
		System.out.println("Name entered : " + inputString);
	 }
  } catch (Exception ex)
  {
	 ex.printStackTrace();
  }
}

2)使用BufferedReader实例读取控制台输入

private static void usingBufferedReader()
{
  System.out.println("Name: ");
  try{
	 BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
	 String inputString = bufferRead.readLine();

	 System.out.println("Name entered : " + inputString);
 }
 catch(IOException ex)
 {
	ex.printStackTrace();
 }
}	

3)使用扫描器实例读取控制台输入

private static void usingScanner()
{
  System.out.println("Name: ");

  Scanner scanIn = new Scanner(System.in);
  String inputString = scanIn.nextLine();

  scanIn.close();            
  System.out.println("Name entered : " + inputString);
}

所有 3 个示例的完整代码

import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class ConsoleInputExamples
{
   public static void main(String[] args)
   {
      usingConsoleReader();
      usingBufferedReader();
      usingScanner();
   }

   private static void usingConsoleReader()
   {
      Console console = null;
      String inputString = null;
      try
      {
         // creates a console object
         console = System.console();
         // if console is not null
         if (console != null)
         {
            // read line from the user input
            inputString = console.readLine("Name: ");
            // prints
            System.out.println("Name entered : " + inputString);
         }
      } catch (Exception ex)
      {
         ex.printStackTrace();
      }
   }

   private static void usingBufferedReader()
   {
      System.out.println("Name: ");
      try{
         BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
         String inputString = bufferRead.readLine();

         System.out.println("Name entered : " + inputString);
     }
     catch(IOException ex)
     {
        ex.printStackTrace();
     }
   }

   private static void usingScanner()
   {
      System.out.println("Name: ");

      Scanner scanIn = new Scanner(System.in);
      String inputString = scanIn.nextLine();

      scanIn.close();            
      System.out.println("Name entered : " + inputString);
   }

}

最重要的是,这三种技术同样有效,但是我个人喜欢java.io.Console方式。 它只是使代码更具可读性。 您有什么选择?