Java 打印写入程序是缓冲写入程序吗
基本上,我想知道PrintWriter是否是缓冲写入程序。 我见过类似于Java 打印写入程序是缓冲写入程序吗,java,inputstream,flush,Java,Inputstream,Flush,基本上,我想知道PrintWriter是否是缓冲写入程序。 我见过类似于PrintWriter pw=newprintwriter(newbufferedwriter(newfilewriter(file)))的代码 然而,来自: 参数: 文件-用作此写入程序目标的文件。如果文件存在,那么它将被截断为零大小;否则,一个新的 文件将被创建。输出将被写入文件并被删除 缓冲 一句话:我认为PrintWriter是缓冲的,因为javadoc“有点提到它”(见引文),如果我不刷新PrintWriter,它
PrintWriter pw=newprintwriter(newbufferedwriter(newfilewriter(file)))的代码代码>
然而,来自:
参数:
文件-用作此写入程序目标的文件。如果文件存在,那么它将被截断为零大小;否则,一个新的
文件将被创建。输出将被写入文件并被删除
缓冲
一句话:我认为PrintWriter是缓冲的,因为javadoc“有点提到它”(见引文),如果我不刷新PrintWriter,它就不会被打印。
你确认我的论文吗?在这种情况下,为什么会有这样的代码:
PrintWriter pw=new PrintWriter(new BufferedWriter(new FileWriter(file))代码>
遗留代码
提前感谢。从技术上讲,它不是一个BufferedWriter
。它直接扩展Writer
。也就是说,它似乎可以使用BufferedWriter
,这取决于您调用的构造函数。例如,请查看传入字符串的构造函数:
public PrintWriter(String fileName) throws FileNotFoundException {
this(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName))),
false);
}
另外,您没有为链接到的javadoc使用构造函数。您使用了接受编写器的构造函数。那一个似乎没有使用缓冲写入程序
。这是它的源代码:
/**
* 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,无需自动换行。
*
*@param输出一个字符输出流
*/
公共打印机(打印输出){
这(出,假);
}
/**
*创建一个新的PrintWriter。
*
*@param输出一个字符输出流
*@param自动刷新布尔值;如果为true,则println,
*printf或format方法将
*刷新输出缓冲区
*/
公共印刷撰稿人(撰稿人),
布尔自动刷新){
超级(出局);
this.out=out;
this.autoFlush=自动刷新;
lineSeparator=java.security.AccessController.doPrivileged(
新的sun.security.action.GetPropertyAction(“line.separator”);
}
Ok因此,如果使用文件名/文件名构造,则隐式使用BufferedWriter,否则必须在构造函数中声明它?不完全如此。这实际上取决于您使用的构造函数。您必须查看源代码才能确定,或者您可以像上面一样创建它,而不必考虑它。如果不缓冲,为什么要使它自动可冲洗?