打印流
java.io.PrintStream为其他输出添加了功能,使它们能够方便的打印各种数据值表示形式。PrintStream具有如下特点:
- 只负责数据的输出,不负责数据的读取
- 与其他输出流不同,它永远不会抛出IOException
- 永远不会抛出IO异常,但是可能抛出别的异常
PrintStream的父类为OutputStream,因此可以使用父类中共性的成员方法。此外,PrintStream还有两个特有的方法:
print()
输出任意类型的值println()
:输出任意类型的值并换行例如我们常使用的
System.out.println()
就是使用了PrintStream中的print()
方法。
/**
* Prints a String and then terminate the line. This method behaves as
* though it invokes <code>{@link #print(String)}</code> and then
* <code>{@link #println()}</code>.
*
* @param x The <code>String</code> to be printed.
*/
public void println(String x) {
synchronized (this) {
print(x);
newLine();
}
}
构造方法:
PrintStream(File file)
:输出目的地是一个文件PrintStream(OutputStream out)
:输出目的地是一个字节流PrintStream(String fileName)
:输出目的地是一个文件路径
在使用PrintStream写数据时,如果使用继承自父类的write方法写数据,那么查看数据的时候会查询编码表;如果使用自己特有的方法print/println方法写数据,那么写的数据原样输出。
public class PrintStreamTest {
public static void main(String[] args) throws FileNotFoundException {
PrintStream ps = new PrintStream("D:\\data\\Code\\Java_code\\src\\IOStream\\test.txt");
ps.write(97); // a
ps.println(97); // 97
ps.close();
}
}
除了写数据外,PrintStream还可以改变输出语句的目的地,即改变信息应该在哪里输出。PrintStream作为System.setOut()
的参数传入,实现输出目的地的改变。
public class PrintStreamTest {
public static void main(String[] args) throws FileNotFoundException {
System.out.println("hello world"); // 在控制台输出
PrintStream ps = new PrintStream("D:\\data\\Code\\Java_code\\src\\IOStream\\test.txt");
System.setOut(ps);
System.out.println("HELLO WORLD"); // 在指定的文件中输出
}
}
除了PrintStream外,还可以使用PrintWriter实现相同的功能。PrintStream、PrintWriter的方法名是完全一致的,PrintWriter类实现了在PrintStream类中的所有print方法,因此一般使用PrintWriter即可。