前言
一般情況下,我們輸出一些字符串到文檔中需要使用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
