java中講講InputStream的用法
InputStream的用法
InputStream 是個(gè)抽象類,有個(gè)抽象方法read(),即一次讀一個(gè)字節(jié)。馬克-to-win:前面我們經(jīng)常用到System.out.println(),實(shí)際上同樣經(jīng)常用的System.in就是Sun編的一個(gè)InputStream的實(shí)例對(duì)象。它的read方法就是一次從控制臺(tái)讀入一個(gè)字節(jié)。下面的實(shí)驗(yàn)會(huì)證明它無(wú)法直接處理中文, 需要將來(lái)用到字符流。馬克- to-win:馬克 java社區(qū):防盜版實(shí)名手機(jī)尾號(hào): 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方法,一次讀一個(gè)字節(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
我們?cè)俅芜\(yùn)行,輸入中文,證明InputStream直接無(wú)法處理中文。
結(jié)果是:
我們
-50
-46
-61
-57
?
?
?
?