基本上我想知道 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/