java读取控制台输入的几种方法:
- jdk1.4及之前用 new BufferedReader(new InputStreamReader(System.in))
- jdk5.0 增加了 java.util.Scanner类
- jdk6.0 增加了 java.io.Console类(但在IDE中获取console会失败)
测试代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
package com.micmiu.app.demo; import java.io.BufferedReader; import java.io.Console; import java.io.InputStreamReader; import java.util.Scanner; /** * java 中控制台输入的几种实现方法 * * @author <a href="http://www.micmiu.com">Michael</a> * @time Create on 2013-10-21 下午4:55:30 * @version 1.0 */ public class ConsoleInput { /** * @param args */ public static void main(String[] args) throws Exception { // jdk1.5 之前的实现方式 test1(); // jdk5.0的Scanner实现方式 // test2(); // jdk6.0中Console实现方式 在IDE中获取console会失败 // test3(); } // jdk1.5 之前的实现方式 public static void test1() throws Exception { String line = null; BufferedReader buffer = new BufferedReader(new InputStreamReader( System.in)); System.out.print("please input :> "); while (!"exit".equals(line = buffer.readLine())) { System.out.println("input context = " + line); System.out.print("please input :> "); } System.out.println("The program will exit"); } // jdk5.0 增加了java.util.Scanner类 public static void test2() { Scanner scanner = new Scanner(System.in); String line = null; System.out.print("please input :> "); while (!"exit".equals(line = scanner.nextLine())) { System.out.println("input context = " + line); System.out.print("please input :> "); } System.out.println("The program will exit"); } // jdk6.0 后增加java.io.Console(但在IDE中获取console会失败) public static void test3() { Console console = System.console(); if (null == console) { System.out.println("Console is unavailable"); System.exit(0); } String line = null; System.out.println(console); while (!"exit".equals(line = console .readLine("please input keyword :> "))) { System.out.println("input context = " + line); } System.out.println("The program will exit"); } } |
运行效果如下:
本文介绍到此结束@Michael Sun.
原创文章,转载请注明: 转载自micmiu – 软件开发+生活点滴[ http://www.micmiu.com/ ]
0 条评论。