1.publicstatic final InputStream in --> 键盘输入
2. publicstatic final PrintStream out --> 屏幕输出
3. publicstatic final PrintStream err --> 错误输出
1. 输入in代码:
InputStream is = System.in;
byte b[] = new byte[11];
System.out.println("请输入内容: ");
try {
int len = is.read(b);
System.out.println("输入内容为: ");
System.out.println(new String(b, 0, len));
} catch (IOException e) {
e.printStackTrace();
}
得出的结果如下图所示:
但是此代码有局限性, 在byte数组定义有限, 所以我们需要需该代码:
System.out.println("请输入内容: ");
int temp = 0;
StringBuffer buf = new StringBuffer();
try {
while((temp=is.read())!=-1){
char c = (char)temp;
if(c=='\n'){
break;
}
buf.append(c);
}
System.out.println("输入内容为: "+buf);
} catch (IOException e) {
e.printStackTrace();
}
}
该代码不够完善当输入中文时会出现乱码,这时需要通过BufferReader来实现.
2. 输出out代码:
OutputStream os = System.out;
try {
os.write("Hello, pite!".getBytes());
os.close();
} catch (IOException e) {
e.printStackTrace();
}
相当于正常的输出代码: System.out.print("Hello, pite!");
3. 错误err输出:
try{
Integer.parseInt("Good morning");
}catch(Exception e){
System.out.println(e);
System.err.println(e);
}
}
System.out.println(e);和System.err.println(e);得出的结果是一样的,代码本身观察不出任何区别, 只有在eclipse下才会有红色的字段出现
.
从概念上来看, System.out.println(e);可以给用户看, 但相反System.err.println(e);是错误的输出, 最好不要给用户看到。