java.io.PrintStream
是 Java 标准库中的一个类,用于输出流中的打印。它提供了一组方便的方法,用于格式化输出和写入数据。PrintStream
类中最常见的使用方式是通过 System.out
和 System.err
进行标准输出和错误输出。
System.out
和 System.err
都是 PrintStream
类的实例,分别用于标准输出流和标准错误输出流。这两个流通常用于向控制台输出信息。
基本概述
- 包:
java.io
- 继承关系:
java.lang.Object
->java.io.OutputStream
->java.io.FilterOutputStream
->java.io.PrintStream
- 实现接口:
Closeable
,Flushable
,Appendable
,AutoCloseable
import java.io.FileNotFoundException;
import java.io.PrintStream;
public class PrintStreamExample {
public static void main(String[] args) {
try (PrintStream ps = new PrintStream("output.txt")) {
ps.println("Hello, World!");
ps.print(123);
ps.print('A');
ps.printf("Formatted string: %.2f", 45.678);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}