1. 程式人生 > >關於PrintWriter 為啥自帶緩衝還要寫成PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")))

關於PrintWriter 為啥自帶緩衝還要寫成PrintWriter = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")))

個人理解:

看了下原始碼

  public PrintWriter (Writer out) {         this(out, false);     }

    /**      * Creates a new PrintWriter.      *      * @param  out        A character-output stream      * @param  autoFlush  A boolean; if true, the <tt>println</tt>,      *                    <tt>printf</tt>, or <tt>format</tt> methods will      *                    flush the output buffer      */     public PrintWriter(Writer out,                        boolean autoFlush) {         super(out);         this.out = out;         this.autoFlush = autoFlush;         lineSeparator = java.security.AccessController.doPrivileged(             new sun.security.action.GetPropertyAction("line.separator"));     }

也就是說引數是BufferedWriter 才會有緩衝 節點流是沒有的 這也是為啥BufferedWriter   api介紹到

常 Writer 將其輸出立即傳送到底層字元或位元組流。除非要求提示輸出,否則建議用 BufferedWriter 包裝所有其 write() 操作可能開銷很高的 Writer(如 FileWriters 和 OutputStreamWriters)。例如,

 PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));
 

將緩衝 PrintWriter 對檔案的輸出。如果沒有緩衝,則每次呼叫 print() 方法會導致將字元轉換為位元組,然後立即寫入到檔案,而這是極其低效的。

再看原始碼

 public PrintWriter(File file) throws FileNotFoundException {         this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file))),              false);     }

public PrintWriter(OutputStream out) {         this(out, false);     }

public PrintWriter(OutputStream out, boolean autoFlush) {         this(new BufferedWriter(new OutputStreamWriter(out)), autoFlush);

        // save print stream for error propagation         if (out instanceof java.io.PrintStream) {             psOut = (PrintStream) out;         }     }

最終都是把形參包裝成BuferedWriter然後呼叫最上面的建構函式