從標準輸入中讀取資料

來源:互聯網
上載者:User

以Unix首先倡導的“標準輸入”、“標準輸出”以及“標準錯誤輸出”概念為基礎,Java提供了相應的System.in,System.out以及System.err。貫這一整本書,大家都會接觸到如何用System.out進行標準輸出,它已預封裝成一個PrintStream對象。System.err同樣是一個PrintStream,但System.in是一個原始的InputStream,未進行任何封裝處理。這意味著儘管能直接使用System.out和System.err,但必須事先封裝System.in,否則不能從中讀取資料。
典型情況下,我們希望用readLine()每次讀取一行輸入資訊,所以需要將System.in封裝到一個DataInputStream中。這是Java 1.0進行行輸入時採取的“老”辦法。在本章稍後,大家還會看到Java 1.1的解決方案。下面是個簡單的例子,作用是回應我們鍵入的每一行內容:
 

//: Echo.java// How to read from standard inputimport java.io.*;public class Echo {  public static void main(String[] args) {    DataInputStream in =      new DataInputStream(        new BufferedInputStream(System.in));    String s;    try {      while((s = in.readLine()).length() != 0)        System.out.println(s);      // An empty line terminates the program    } catch(IOException e) {      e.printStackTrace();    }  }} ///:~

之所以要使用try塊,是由於readLine()可能“擲”出一個IOException。注意同其他大多數流一樣,也應對System.in進行緩衝。
由於在每個程式中都要將System.in封裝到一個DataInputStream內,所以顯得有點不方便。但採用這種設計方案,可以獲得最大的靈活性。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.