Java從控制台讀入資料的幾種方法

來源:互聯網
上載者:User

這裡記錄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;    }}
 

(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 的控制台中

public class TestConsole3 {    public static void main(String[] args) {        String str = readDataFromConsole("Please input string:");        System.out.println("The information from console:" + str);    }    /**     * Use  java.io.console to read data from console     *      * @param prompt     *      * @return input string     */    private static String readDataFromConsole(String prompt) {        Console console = System.console();        if (console == null) {            throw new IllegalStateException("Console is not available!");        }        return console.readLine(prompt);    }}
 
Console類還有個特色就是,專門對密碼(輸入無回顯)等安全字元,進行了處理。專門提供 readPassword()方法,具體應用見如下代碼:
public class TestConsole5 {         public static void main(String[] args) {            Console console = System.console();            if (console == null) {                throw new IllegalStateException("Console is not available!");            }                        while(true){            String username = console.readLine("Username: ");            char[] password = console.readPassword("Password: ");            if (username.equals("Chris") && String.valueOf(password).equals("GoHead")) {              console.printf("Welcome to Java Application %1$s.\n", username);             // 使用後應立即將數組清空,以減少其在記憶體中佔用的時間,增強安全性                password = null;              System.exit(-1);            }             else {              console.printf("Invalid username or password.\n");            }            }          }}

 

參考資料:

(1)Java從控制台中讀取資料完全攻略

(2)用java.io.Console來與字元控制台互動

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.