是一个PrintWriter和BufferedWriter

2024-02-19

基本上我想知道 PrintWriter 是否是缓冲写入器。 我见过这样的代码PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));然而从这个javadoc http://docs.oracle.com/javase/7/docs/api/java/io/PrintWriter.html#PrintWriter%28java.io.OutputStream,%20boolean%29:

参数: file - 用作此编写器的目标的文件。如果文件存在,那么它将被截断为零大小;否则,一个新的 将创建文件。输出将被写入文件并且是 缓冲的。

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

提前致谢。


从技术上讲,它不是一个BufferedWriter。它直接延伸Writer。这么说来,好像是这样can use a BufferedWriter取决于您调用的构造函数。例如,看看传入 a 的构造函数String:

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

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

/**
 * 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"));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

是一个PrintWriter和BufferedWriter 的相关文章

随机推荐