打印流

java.io.PrintStream为其他输出添加了功能,使它们能够方便的打印各种数据值表示形式。PrintStream具有如下特点:

  • 只负责数据的输出,不负责数据的读取
  • 与其他输出流不同,它永远不会抛出IOException
  • 永远不会抛出IO异常,但是可能抛出别的异常

PrintStream的父类为OutputStream,因此可以使用父类中共性的成员方法。此外,PrintStream还有两个特有的方法:

  • print()输出任意类型的值

  • println():输出任意类型的值并换行

    例如我们常使用的System.out.println()就是使用了PrintStream中的print()方法。

  1. /**
  2. * Prints a String and then terminate the line. This method behaves as
  3. * though it invokes <code>{@link #print(String)}</code> and then
  4. * <code>{@link #println()}</code>.
  5. *
  6. * @param x The <code>String</code> to be printed.
  7. */
  8. public void println(String x) {
  9. synchronized (this) {
  10. print(x);
  11. newLine();
  12. }
  13. }

构造方法:

  • PrintStream(File file):输出目的地是一个文件
  • PrintStream(OutputStream out):输出目的地是一个字节流
  • PrintStream(String fileName):输出目的地是一个文件路径

在使用PrintStream写数据时,如果使用继承自父类的write方法写数据,那么查看数据的时候会查询编码表;如果使用自己特有的方法print/println方法写数据,那么写的数据原样输出。

  1. public class PrintStreamTest {
  2. public static void main(String[] args) throws FileNotFoundException {
  3. PrintStream ps = new PrintStream("D:\\data\\Code\\Java_code\\src\\IOStream\\test.txt");
  4. ps.write(97); // a
  5. ps.println(97); // 97
  6. ps.close();
  7. }
  8. }

除了写数据外,PrintStream还可以改变输出语句的目的地,即改变信息应该在哪里输出。PrintStream作为System.setOut()的参数传入,实现输出目的地的改变。

  1. public class PrintStreamTest {
  2. public static void main(String[] args) throws FileNotFoundException {
  3. System.out.println("hello world"); // 在控制台输出
  4. PrintStream ps = new PrintStream("D:\\data\\Code\\Java_code\\src\\IOStream\\test.txt");
  5. System.setOut(ps);
  6. System.out.println("HELLO WORLD"); // 在指定的文件中输出
  7. }
  8. }

除了PrintStream外,还可以使用PrintWriter实现相同的功能。PrintStream、PrintWriter的方法名是完全一致的,PrintWriter类实现了在PrintStream类中的所有print方法,因此一般使用PrintWriter即可。