本文介绍了PrintWriter是BufferedWriter吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我想知道PrintWriter是否是Buffered Writer。
我见过代码如 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
但是来自此的Javadoc

Basically I would like to know whether or not the PrintWriter is a Buffered Writer.I have seen code like PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));However from this javadoc:

底线:我认为PrintWriter是缓冲的,因为javadoc有点提到它(见报价),如果我不刷新PrintWriter,它就不会被打印出来。
你确认我的论文吗?在这种情况下,为什么会有一些代码如下:
PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
遗留代码?

Bottom line: I think that PrintWriter is buffered since the javadoc "kind of mention it" (see the quote) and if I don't flush a PrintWriter it does not get printed.Do you confirm my thesis? In that case why there is some code that goes like:PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));legacy code?

提前致谢。

推荐答案

从技术上讲,它不是 BufferedWriter 。它直接扩展 Writer 。也就是说,似乎可以使用 BufferedWriter ,具体取决于您调用的构造函数。例如,查看传递 String 的构造函数:

Technically, it is not a BufferedWriter. It directly extends Writer. That said, it seems like it can use a BufferedWriter depending on the constructor you call. For exampe look at the constructor that passes in a String:

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

另外,你没有使用你链接的javadoc的构造函数至。你已经使用了带 Writer 的构造函数。那个似乎没有使用 BufferedWriter 。这是它的源代码:

Also, you're not using the constructor for the javadoc you've linked to. You've used the constructor that takes a Writer. That one does not seem to use a BufferedWriter. This is its source code:

/**
 * Creates a new PrintWriter, without automatic line flushing.
 *
 * @param  out        A character-output stream
 */
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"));
}

这篇关于PrintWriter是BufferedWriter吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!