System.out对象就是一个典型的PrintStream流对象,下面的例子均以System.out对象为例,介绍PrintStream的常用方法

print

可以将传入的参数输出到屏幕或者其他终端(需要绑定对应的流对象)

有如下重载形式

image-20220906172114530

1
2
3
4
5
rintStream out = System.out;
out.print(9);
out.print('8');
// 输出:
// 98

println

可以将传入的参数输出到屏幕或者其他终端(需要绑定对应的流对象),在输出的最后会输出换行

有如下重载形式

image-20220906193735534

1
2
3
4
5
6
PrintStream out = System.out;
out.println(8);
out.println('9');
// 输出:
// 9
// 8

printf

将内容进行格式化输出,有点类似C语言的printf函数

有如下重载形式

image-20220906194015140

1
2
3
4
PrintStream out = System.out;
out.printf("%d", 3);
// 输出结果:
// 3

format

用法同printf

有如下重载形式

image-20220906194725412

1
2
PrintStream out = System.out;
out.format("%d", 5);

checkerr

刷新流并检查其错误状态

public boolean checkError()

1
2
PrintStream out = System.out;
out.checkError();

flush

刷新流

public void flush()

1
2
PrintStream out = System.out;
out.flush();

close

关闭流

public void close()

1
2
PrintStream out = System.out;
out.close();

输出内容到文件

默认输出到终端,但是我们可以设置输出内容到文件

通过System.setOut方法来改变printStream流

public static void setOut(PrintStream out)

注意:System.in和System.err分别对应InputStream和PrintStream

  1. System.setIn可以改变输入来源,默认为键盘

public static void setIn(InputStream in)

  1. System.seterr可以改变错误流的输出位置,默认为控制台,System.err使用方式和System.out差不多

public static void setErr(PrintStream err)

  1. printWriter用法同PrintStream
1
2
3
4
5
6
7
8
// 输出内容到news.txt
System.setOut(new PrintStream("E:\\news.txt"));
// 输出4行"hello,world"
System.out.println("hello,world");
System.out.println("hello,world");
System.out.println("hello,world");
System.out.println("hello,world");

结果:

image-20220906200500712