四十六、打印流

一、打印流概述

打印流添加输出数据的功能,使它们能够方便地打印各种数据值表示形式.
打印流根据流的分类:

  • 字节打印流 PrintStream
  • 字符打印流 PrintWriter
  • 方法:
    void print(String str): 输出任意类型的数据。
    void println(String str): 输出任意类型的数据,自动写入换行操作。
/* 
 * 需求:把指定的数据,写入到printFile.txt文件中
 * 
 * 分析:
 *  1,创建流
 *  2,写数据
 *  3,关闭流
 */
public class PrintWriterDemo {
    public static void main(String[] args) throws IOException {
        //创建流
        //PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"));
        PrintWriter out = new PrintWriter("printFile.txt");
        //2,写数据
        for (int i=0; i<5; i++) {
            out.println("helloWorld");
        }
        //3,关闭流
        out.close();
    }
}

二、打印流数据自动刷新

在没有刷新前,你写入的数据并没有真正写入文件,只是保存在内存中。刷新后才会写入文件,如果程序中没有调用刷新方法,当程序执行完时会自动刷新,也就是只有到数据全部执行完才会一次性写入,大数据量时对运行效率有影响。
可以通过构造方法,完成文件数据的自动刷新功能。

  • 构造方法:
  • 开启文件自动刷新写入功能
    public PrintWriter(OutputStream out, boolean autoFlush)
    public PrintWriter(Writer out, boolean autoFlush)
 /* 
 * 分析:
 *  1,创建流
 *  2,写数据
 */
public class PrintWriterDemo2 {
    public static void main(String[] args) throws IOException {
        //创建流
        PrintWriter out = new PrintWriter(new FileWriter("printFile.txt"), true);
        //2,写数据
        for (int i=0; i<5; i++) {
            out.println("helloWorld");
        }
        //3,关闭流
        out.close();
    }
}

三、实例:使用Scanner和PrintWriter完成文件的复制

注意:PrintWriter.print()写入文件的换行符要"\r\n" ,而不是 "\n"。

public class PrintWriterDemo2 {
    public static void main(String[] args) throws IOException {
        Scanner in=new Scanner(Paths.get("printFile.txt"),"utf-8");
        String str=new String();
        while(in.hasNext()){
            str += in.nextLine()+"\r\n";

        }
        System.out.print(str);
        PrintWriter out=new PrintWriter("printFile2.txt");
        out.write(str);
        in.close();
        out.close();
    }
}

你可能感兴趣的:(四十六、打印流)