Java学习 PrintWriter打印输出—用于快速输出字符到文件

前言

  一般情况下,我们输出一些字符串到文档中需要使用FileWriter与BufferedWriter配合。但是使用这方式效率并不高,在有大量日志或者字符串需要输出到文档中的情况下更推荐使用PrintWriter

简单的demo

    private void write(){
        File file = new File(getExternalCacheDir().getPath(), "demo.txt");
        try {
            PrintWriter printWriter = new PrintWriter(file);//PrintWriter会自动判断文件是否存在,如果不存在会自动创建目录与文件
            printWriter.print("写入内容1");//print方法不会调用flush
            printWriter.println("写入内容2");//使用println方法写入内容会自动在底层调用flush方法,println会影响些许性能,因为时刻将字符串输出到文件中,但是有及时性
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

注意! 这个demo,并不会自动在文件的后续追加内容,所以你会看到文档只有一小部分内容。

在输出文档的尾部追加写入内容的demo

private void write(){
        File file = new File(getExternalCacheDir().getPath(), "demo.txt");
        FileWriter fileWriter = null;
        PrintWriter printWriter = null;
        try {
            fileWriter = new FileWriter(file, true);//这里设置的true就是设置在文档后面追加内容
            printWriter = new PrintWriter(fileWriter, true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if (printWriter != null){
                printWriter.close();
                printWriter = null;
            }
            if (fileWriter != null){
                try {
                    fileWriter.close();
                    fileWriter = null;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

end

猜你喜欢

转载自www.cnblogs.com/guanxinjing/p/12170756.html