java中講講InputStream的用法
InputStream的用法
InputStream 是個抽象類,有個抽象方法read(),即一次讀一個字節(jié)。馬克-to-win:前面我們經(jīng)常用到System.out.println(),實際上同樣經(jīng)常用的System.in就是Sun編的一個InputStream的實例對象。它的read方法就是一次從控制臺讀入一個字節(jié)。下面的實驗會證明它無法直接處理中文, 需要將來用到字符流。馬克- to-win:馬克 java社區(qū):防盜版實名手機尾號: 73203。
例: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方法,一次讀一個字節(jié)。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();
}
for (int i = 0; i < 4; i++) {
System.out.println(inp[i]);//打出數(shù)字
}
for (int i = 0; i < 4; i++) {
System.out.println((char) inp[i]);//打出字符
}
}
}
結(jié)果:
abcd
97
98
99
100
a
b
c
d
我們再次運行,輸入中文,證明InputStream直接無法處理中文。
結(jié)果是:
我們
-50
-46
-61
-57
?
?
?
?