java.io
包中的PrintStream
类可以用来写入以通常可读形式(文本)而不是字节形式的输出数据。
它扩展了抽象类OutputStream
。
PrintStream的工作原理
与其它输出流不同,PrintStream
将原始数据 (整数、字符)转换为文本格式而不是字节。然后它将格式化后的数据写入输出流。
另外,PrintStream
类不抛出任何输入/输出异常。相反,我们需要使用checkError()
方法来查找其中的任何错误。
注意:PrintStream
类还具有自动刷新功能。这意味着它会在以下任一条件下强制输出流将所有数据写入目标:
- 在打印流中写入换行符
\n
- 调用了
println()
方法 - 在打印流中写入了字节数组
创建PrintStream
要创建PrintStream
,我们必须先导入java.io.PrintStream
包。导入包后,我们可以这样创建打印流。
1. 使用其他输出流
// Creates a FileOutputStream
FileOutputStream file = new FileOutputStream(String file);
// Creates a PrintStream
PrintStream output = new PrintStream(file, autoFlush);
这里,
- 我们创建了一个打印流,它会将格式化数据写入由
FileOutputStream
表示的文件。 autoFlush
是一个可选的布尔参数,指定是否执行自动刷新。
2. 使用文件名
// Creates a PrintStream
PrintStream output = new PrintStream(String file, boolean autoFlush);
这里,
- 我们创建了一个打印流,它会将格式化数据写入指定的文件。
autoFlush
是一个可选的布尔参数,指定是否执行自动刷新。
注意:在这两种情况下,PrintStream
都使用某种默认字符编码将数据写入文件。但是,我们也可以指定字符编码(UTF8或UTF16)。
// Creates a PrintStream using some character encoding
PrintStream output = new PrintStream(String file, boolean autoFlush, Charset cs);
在这里,我们使用了Charset
类来指定字符编码。要了解更多信息,请访问Java Charset(官方Java文档)。
PrintStream的方法
PrintStream
类提供了各种方法,允许我们将数据打印到输出。
print() 方法
print()
- 将指定数据打印到输出流。println()
- 将数据打印到输出流,并在末尾添加一个换行符。
示例:使用System类打印()方法
class Main {
public static void main(String[] args) {
String data = "Hello World.";
System.out.print(data);
}
}
输出
Hello World.
在上面的示例中,我们没有创建打印流。但是,我们可以使用PrintStream
类的print()
方法。
你可能想知道这是如何实现的。让我来解释一下这里发生了什么。
注意这行:
System.out.print(data);
这里,
System
是一个最终类,负责执行标准的输入/输出操作。out
是System
类中声明的PrintStream
类型的类变量。
既然out
是PrintStream
类型,我们就可以用它来调用PrintStream
类的所有方法。
示例:使用PrintStream类打印()方法
import java.io.PrintStream;
class Main {
public static void main(String[] args) {
String data = "This is a text inside the file.";
try {
PrintStream output = new PrintStream("output.txt");
output.print(data);
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
在上面的示例中,我们创建了一个名为output的打印流。该打印流与output.txt文件关联。
PrintStream output = new PrintStream("output.txt");
为了打印数据到文件,我们使用了print()
方法。
这里,当我们运行程序时,output.txt文件将包含以下内容。
This is a text inside the file.
printf() 方法
printf()
方法可用于打印格式化字符串。它包含2个参数:格式化字符串和参数。例如,
printf("I am %d years old", 25);
这里,
- I am %d years old 是一个格式化字符串
- %d是格式化字符串中的整数数据
- 25 是一个参数
格式化字符串包含文本和数据。参数会替换格式化字符串中的数据。
因此,%d被25替换。
示例:使用PrintStream的printf()方法
import java.io.PrintStream;
class Main {
public static void main(String[] args) {
try {
PrintStream output = new PrintStream("output.txt");
int age = 25;
output.printf("I am %d years old.", age);
output.close();
}
catch(Exception e) {
e.getStackTrace();
}
}
}
在上面的示例中,我们创建了一个名为output的打印流。该打印流与文件output.txt关联。
PrintStream output = new PrintStream("output.txt");
为了将格式化文本打印到文件,我们使用了printf()
方法。
这里,当我们运行程序时,output.txt文件将包含以下内容。
I am 25 years old.
PrintStream的其他方法
方法 | 描述 |
---|---|
close() |
关闭打印流。 |
checkError() |
检查流中是否有错误,并返回布尔结果。 |
append() |
将指定数据追加到流。 |
要了解更多信息,请访问Java PrintStream(官方Java文档)。