Java IO 之 读取控制台输入

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

目录

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

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


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方式。它只是使代码更具可读性。您有什么选择?

saigon has written 1445 articles