在System类中定义了三个操作的常量。
- 标准输出(显示器) : public final static PrintStream out
- 错误输出 : public final static PrintStream err
- 标准输入(键盘):public final static InputStream in
一、系统输出流
由于System.out是PrintStream的实例化对象,而PrintStream又是OutputStream的子类,所以可以直接使用System.out直接为OutputStream实例化,这个时候OutputStream输出的位置将变为屏幕。
系统输出一共有两个常量:out、err,并且这两个常量表示的都是PrintStream类的对象。
- out输出的是希望用户能看到的内容
- err输出的是不希望用户看到的内容,会在屏幕显示红色
范例:使用System.out为OutputStream实例化。
public class TestPrintf {
//输出到屏幕
public static void main(String[] args) throws Exception {
OutputStream out = System.out;
out.write("ee".getBytes());
}
}
二、 系统输入流
//直到用户输入完成(按下回车),
//程序才能继续向下执行。
public class TestPrintf {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
byte[] data = new byte[1024];
System.out.print("输出信息");
int temp = in.read(data);
System.out.println("输出 " + new String(data, 0, temp));
}
}
public class TestPrintf {
public static void main(String[] args) throws IOException {
InputStream in = System.in;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] data = new byte[10];
System.out.print("请输入信息:");
int temp = 0;
while ((temp = in.read(data)) != -1) {
// 保存数据到内存输出流中
// 这里面需要用户判断是否输入结束
bos.write(data, 0, temp);
if (temp>data.length) {
break;
}
in.close();
bos.close();
System.out.println("输出内容为:"+new String (bos.toByteArray()));
}
}
}