這裡記錄Java中從控制台讀入信息的幾種方式,已備後查!
(1)JDK 1.4(JDK 1.5和JDK 1.6也都兼容這種方法)
- public class TestConsole1 {
- public static void main(String[] args) {
- String str = readDataFromConsole("Please input string:);
- System.out.println("The information from console: + str);
- }
- /**
- * Use InputStreamReader and System.in to read data from console
- *
- * @param prompt
- *
- * @return input string
- */
- private static String readDataFromConsole(String prompt) {
- BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
- String str = null;
- try {
- System.out.print(prompt);
- str = br.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return str;
- }
- }
(2)JDK 1.5(利用Scanner進行讀取)
- public class TestConsole2 {
- public static void main(String[] args) {
- String str = readDataFromConsole("Please input string:");
- System.out.println("The information from console:" + str);
- }
- /**
- * Use java.util.Scanner to read data from console
- *
- * @param prompt
- *
- * @return input string
- */
- private static String readDataFromConsole(String prompt) {
- Scanner scanner = new Scanner(System.in);
- System.out.print(prompt);
- return scanner.nextLine();
- }
- }
Scanner還可以很方便的掃描文件,讀取裡面的信息並轉換成你要的類型,比如對“2 2.2 3.3 3.33 4.5 done”這樣的數據求和,見如下代碼:
- public class TestConsole4 {
- public static void main(String[] args) throws IOException {
- FileWriter fw = new FileWriter("num.txt");
- fw.write("2 2.2 3.3 3.33 4.5 done");
- fw.close();
- System.out.println("Sum is "+scanFileForSum("num.txt"));
- }
- public static double scanFileForSum(String fileName) throws IOException {
- double sum = 0.0;
- FileReader fr = null;
- try {
- fr = new FileReader(fileName);
- Scanner scanner = new Scanner(fr);
- while (scanner.hasNext()) {
- if (scanner.hasNextDouble()) {
- sum = sum + scanner.nextDouble();
- } else {
- String str = scanner.next();
- if (str.equals("done")) {
- break;
- } else {
- throw new RuntimeException("File Format is wrong!");
- }
- }
- }
- } catch (FileNotFoundException e) {
- throw new RuntimeException("File " + fileName + " not found!");
- } finally {
- if (fr != null)
- fr.close();
- }
- return sum;
- }
- }