天天看點

java中講講InputStream的用法,舉例?

2.1 InputStream的用法

InputStream 是個抽象類,有個抽象方法read(),即一次讀一個位元組。馬克-to-win:前面我們經常用到System.out.println(),實際上同樣 經常用的System.in就是Sun編的一個InputStream的執行個體對象。它的read方法就是一次從控制台讀入一個位元組。下面的實驗會證明它無 法直接進行中文, 需要将來用到字元流。

例:2.1.1

import java.io.*;

public class TestMark_to_win {

    public static void main(String args[]) throws Exception {

        byte inp[] = new byte[4];

        for (int i = 0; i < 4; i++) {

/* 這裡的read方法,一次讀一個位元組。Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255.  so you must cast by yourself. when you run, you type in abcd, This method blocks until input

 data is available,

*/

            inp[i] = (byte) System.in.read();

        }

            System.out.println(inp[i]);//打出數字

            System.out.println((char) inp[i]);//打出字元

    }

}