本帖最后由 杨兴庭 于 2013-7-21 12:31 编辑
public class Text {
public static void main(String[] args) throws IOException {
InputStreamIn();
InputStreamToReader();
}
/**
* 利用InputStream循环输入并输出
*/
public static void InputStreamIn() {
InputStream input = System.in;
int r = 0;
StringBuffer buf = new StringBuffer();
System.out.println("请录入数据");
try {
while ((r = input.read()) != -1) {
if (r == '\r')
continue;
if (r == '\n') {
System.out.println(buf.toString());
buf.delete(0, buf.length());
} else {
buf.append((char) r);
}
if (buf.toString().equalsIgnoreCase("over"))
break;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("结束");
}
/**
* 字节流转换成字符流后然后用字符流缓冲区读取
*/
public static void InputStreamToReader() {
System.out.println("请输入");
InputStream in = System.in;// 定义了键盘输入流字节流
InputStreamReader reder = new InputStreamReader(in);// 字节流转换成字符流
BufferedReader bufRea = new BufferedReader(reder);// 利用缓冲区提高效率
String line = null;
try {
while ((line = bufRea.readLine()) != null) {
if (line.equalsIgnoreCase("over")) {
break;
}
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
reder.close();
bufRea.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("结束");
}
}
结果:
疑问:为什么用InputStream字节流输入后,然后读取汉字的话输出的不是汉字呢,
若把字节流转换成字符流,然后读取,读取汉字后,输出的是正确的汉字,还请各位帮忙解释一下。
|
|