1. 程式人生 > >java IO(四):鍵盤錄入

java IO(四):鍵盤錄入

buffered implement 默認 gre ace hit break println repr

要讀取鍵盤輸入的數據,需要使用輸入流,可以是字節輸入流,也可以是字節輸入流轉換後的字符輸入流。

關於鍵盤輸入,有幾點註意的是:
(1).鍵盤輸入流為System.in,其返回的是InputStream類型,即字節流。
(2).字節流讀取鍵盤的輸入時,需要考慮回車符(\r:13)、換行符(\n:10)。
(3).按行讀取鍵盤輸入時,需要指定輸入終止符,否則輸入將被當作here String文本,而非document。
(4).System.in字節流默認一直處於打開狀態,可不用對其close(),但如果close()了,後續將不能使用in流。

例如,以字節輸入流讀取輸入,此時只能輸入ascii碼中的符號。如果需要讀取中文字符,使用字節流則需要加很多額外的代碼來保證中文字符的字節不會被切分讀取。

import java.io.*;

public class KeyB {
    public static void main(String[] args) throws IOException {
        InputStream in = System.in;
        int ch = in.read();
        System.out.println(ch);
        int ch1 = in.read();
        System.out.println(ch1);
        int ch2 = in.read();
        System.out
.println(ch2); int ch3 = in.read(); System.out.println(ch3); int ch4 = in.read(); System.out.println(ch4); } }

以上示例中,將讀取鍵盤上輸入的5個字節,例如輸入"ab"回車後,將輸出"ab\r\n"的ascii碼(97-98-13-10),並繼續等待輸入下一個字節才退出。

要想一次性讀取一行,可以將它們讀取到字節數組中,並以回車符、換行符判斷一行讀取完畢,再將字節數組轉換為字符串輸出。雖然用字節流能夠完成這樣的操作,但顯然,如果使用字符流,則更輕松。

import java.io.*;

public class KeyB {
    public static void main(String[] args) throws IOException {

        //InputStream in = System.in   //鍵盤輸入字節流
        //InputStreamReader isr = new InputStreamReader(in);   //橋梁,將字節流轉換為字符流
        //BufferedReader bufr = new BufferedReader(isr);       //以BufferReader的readLine()讀取行
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));

        String line = null;
        //line = bufr.readLine();System.out.println(line);   //輸入一行立即退出
        while((line = bufr.readLine())!=null) {      //循環輸入多行,直到輸入終止符時才退出
            if (line.equals("quit")) {   //定義鍵盤輸入終止符quit
                break;
            }
            System.out.println(line);
        }
    }
}

註意,BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));幾乎是涉及到鍵盤錄入時的一條固定代碼,屬於可以直接背下來的。

以下是一個示例,需求是將鍵盤輸入的結果保存到文件d:\myjava\a.txt中。

import java.io.*;

public class Key2File {
    public static void main(String[] args) throws IOException {
        //1.源:鍵盤輸入,目標:文件
        //2.輸入中可能包含中文字符,所以采用字符流,輸出也采用字符流
        //3.需要使用Buffered流來提高效率並使用其提供的行操作方法
        BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufw = new BufferedWriter(new FileWriter("d:/myjava/a.txt"));

        String line = null;
        while((line=bufr.readLine())!=null) {
            if(line.equals("quit")) {
                break;
            }
            bufw.write(line);
            bufw.newLine();
            bufw.flush();
        }
        bufw.close();
    }
}

註:若您覺得這篇文章還不錯請點擊右下角推薦,您的支持能激發作者更大的寫作熱情,非常感謝!

java IO(四):鍵盤錄入