PrintWriter是BufferedWriter吗?
基本上我想知道PrintWriter是否是Buffered Writer。 我见过类似PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
代码PrintWriter pw = new PrintWriter(new BufferedWriter(new FileWriter(file)));
但是从这个javadoc :
参数:file – 用作此writer的目标的文件。 如果该文件存在,那么它将被截断为零大小; 否则,将创建一个新文件。 输出将写入文件并进行缓冲。
一句话:我认为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 println, * printf, or format 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")); }