【问题标题】:Is a PrintWriter a BufferedWriter是 PrintWriter 和 BufferedWriter
【发布时间】:2013-06-20 20:30:30
【问题描述】:

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

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

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

提前致谢。

【问题讨论】:

    标签: java inputstream flush


    【解决方案1】:

    从技术上讲,它不是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"));
    }
    

    【讨论】:

    • 好的,如果用文件/文件名构造它隐式使用 BufferedWriter 否则它必须在构造函数中声明?
    • 不完全是。这实际上取决于您使用的构造函数。您必须查看来源以确定,或者您可以像上面那样创建它,而不必考虑它。
    • 如果没有缓冲,为什么要让它自动刷新?
    猜你喜欢
    • 1970-01-01
    • 2013-03-26
    • 2019-02-10
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 2023-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多