打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Java 字符终端上获取输入三种方式

在Java 字符终端上获取输入有三种方式:

1、java.lang.System.in (目前JDK版本均支持)

2、java.util.Scanner (JDK版本>=1.5)

3、java.io.Console(JDK版本>=1.6),特色:能不回显密码字符



参考:

这里记录Java中从控制台读入信息的几种方式

(1)JDK 1.4(JDK 1.5和JDK 1.6也都兼容这种方法)

  1. public class TestConsole1 {  
  2.     public static void main(String[] args) {  
  3.         String str = readDataFromConsole("Please input string:);  
  4.         System.out.println("The information from console: + str);  
  5.     }  
  6.   
  7.     /** 
  8.      * Use InputStreamReader and System.in to read data from console 
  9.      *  
  10.      * @param prompt 
  11.      *             
  12.      * @return input string 
  13.      */  
  14.     private static String readDataFromConsole(String prompt) {  
  15.         BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  
  16.         String str = null;  
  17.         try {  
  18.             System.out.print(prompt);  
  19.             str = br.readLine();  
  20.   
  21.         } catch (IOException e) {  
  22.             e.printStackTrace();  
  23.         }  
  24.         return str;  
  25.     }  
  26. }  
 

(2)JDK 1.5(利用Scanner进行读取)

  1. public class TestConsole2 {  
  2.     public static void main(String[] args) {  
  3.         String str = readDataFromConsole("Please input string:");  
  4.         System.out.println("The information from console:" + str);  
  5.     }  
  6.   
  7.     /** 
  8.      * Use  java.util.Scanner to read data from console 
  9.      *  
  10.      * @param prompt 
  11.      *  
  12.      * @return input string 
  13.      */  
  14.     private static String readDataFromConsole(String prompt) {  
  15.         Scanner scanner = new Scanner(System.in);  
  16.         System.out.print(prompt);  
  17.         return scanner.nextLine();  
  18.     }  
  19. }  
 
Scanner还可以很方便的扫描文件,读取里面的信息并转换成你要的类型,比如对“2 2.2 3.3 3.33 4.5 done”这样的数据求和,见如下代码:
 
 
  1. public class TestConsole4 {  
  2.   
  3.     public static void main(String[] args) throws IOException {  
  4.         FileWriter fw = new FileWriter("num.txt");  
  5.         fw.write("2 2.2 3.3 3.33 4.5 done");  
  6.         fw.close();  
  7.   
  8.         System.out.println("Sum is "+scanFileForSum("num.txt"));  
  9.     }  
  10.   
  11.     public static double scanFileForSum(String fileName) throws IOException {  
  12.         double sum = 0.0;  
  13.         FileReader fr = null;  
  14.         try {  
  15.             fr = new FileReader(fileName);  
  16.             Scanner scanner = new Scanner(fr);  
  17.               
  18.             while (scanner.hasNext()) {  
  19.                 if (scanner.hasNextDouble()) {  
  20.                     sum = sum + scanner.nextDouble();  
  21.   
  22.                 } else {  
  23.                     String str = scanner.next();  
  24.   
  25.                     if (str.equals("done")) {  
  26.                         break;  
  27.                     } else {  
  28.                         throw new RuntimeException("File Format is wrong!");  
  29.                     }  
  30.   
  31.                 }  
  32.             }  
  33.   
  34.         } catch (FileNotFoundException e) {  
  35.             throw new RuntimeException("File " + fileName + " not found!");  
  36.         } finally {  
  37.             if (fr != null)  
  38.                 fr.close();  
  39.         }  
  40.         return sum;  
  41.     }  

(3)JDK 1.6(利用java.io.Console进行读取)

JDK6中提供了java.io.Console类专用来访问基于字符的控制台设备. 
你的程序如果要与Windows下的cmd或者Linux下的Terminal交互,就可以用Console类代劳.(类似System.in和System.out) 
但我们不总是能得到可用的Console, 一个JVM是否有可用的Console依赖于底层平台和JVM如何被调用. 
如果JVM是在交互式命令行(比如Windows的cmd)中启动的,并且输入输出没有重定向到另外的地方,那么就可以得到一个可用的Console实例。

在使用 IDE 的情况下,是无法获取到Console实例的,原因在于在 IDE 的环境下,重新定向了标准输入和输出流,也是就是将系统控制台上的输入输出重定向到了 IDE 的控制台中

  1. public class TestConsole3 {  
  2.     public static void main(String[] args) {  
  3.         String str = readDataFromConsole("Please input string:");  
  4.         System.out.println("The information from console:" + str);  
  5.     }  
  6.   
  7.     /** 
  8.      * Use  java.io.console to read data from console 
  9.      *  
  10.      * @param prompt 
  11.      *  
  12.      * @return input string 
  13.      */  
  14.     private static String readDataFromConsole(String prompt) {  
  15.         Console console = System.console();  
  16.         if (console == null) {  
  17.             throw new IllegalStateException("Console is not available!");  
  18.         }  
  19.         return console.readLine(prompt);  
  20.     }  
  21. }  
 
Console类还有个特色就是,专门对密码(输入无回显)等安全字符,进行了处理。专门提供 readPassword()方法,具体应用见如下代码:
  1. public class TestConsole5 {  
  2.       
  3.      public static void main(String[] args) {  
  4.             Console console = System.console();  
  5.             if (console == null) {  
  6.                 throw new IllegalStateException("Console is not available!");  
  7.             }  
  8.               
  9.             while(true){  
  10.             String username = console.readLine("Username: ");  
  11.             char[] password = console.readPassword("Password: ");  
  12.   
  13.             if (username.equals("Chris") && String.valueOf(password).equals("GoHead")) {  
  14.               console.printf("Welcome to Java Application %1$s.\n", username);  
  15.              // 使用后应立即将数组清空,以减少其在内存中占用的时间,增强安全性   
  16.                 password = null;  
  17.               System.exit(-1);  
  18.             }   
  19.             else {  
  20.               console.printf("Invalid username or password.\n");  
  21.             }  
  22.             }  
  23.           }  
  24.   

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
java从控制台读入数据
java基础习题(一)
Java键盘输入
Java中输入与输出的方法总结
输入
​FinallShell离线激活步骤,适用MAC/WIN
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服