浅析Java中的IO流(五)

97 阅读2分钟

文章目录

打印流

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

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

PrintStream的父类为OutputStream,因此可以使用父类中共性的成员方法。

  • public void close():关闭此输出流并释放与此相关的任何系统资源
  • public void flush():刷新此输出流并强制任何缓冲的输出字节被写入
  • public void write(byte[] b): 将b.length的字节从指定的字符数组写入此输出流
  • public void write(byte[] b, int off, int len): 从指定的字节数组写入len长度的字节,从偏移量off开始输出到此输出流中
  • public abstract void write(int b):将指定的字节输出流

此外,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即可。