java - 是一个 PrintWriter 和 BufferedWriter

标签 java inputstream flush

基本上我想知道 PrintWriter 是否是缓冲写入器。 我见过像 PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file))); 这样的代码 然而来自this javadoc :

Parameters: file - The file to use as the destination of this writer. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

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

提前致谢。

最佳答案

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

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

此外,您没有使用链接到的 javadoc 的构造函数。您已经使用了带有 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"));
}

关于java - 是一个 PrintWriter 和 BufferedWriter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17223211/

相关文章:

Perl 套接字 (IO::Socket::INET6) 没有自动刷新

java - 在 Maven test/resources 目录中创建和删除文件

python - 如何用 python 编写处理文本流的程序?

java - HttpURLConnection返回的InputStream中的数据在读取之前存储在哪里?

c++ - 如何在 C++ 中刷新重定向的标准输出

php - 如何在 PHP 中设置定时器?

java - 将 JS 数组作为 List<> 传递给 Spring MVC Controller

java - 打开包含字符串 intellij 的文件

java - 继承问题(java)

java - Android - 将 JSON 从 InputStream 保存到字符串中