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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM