System.out.write方法是否刷新流?

时间:2014-06-25 12:42:27

标签: java

public class Test {
 public static void main(String..args) {
    System.out.println("Testing.");
    System.out.print("Testing Again.");
    }
  }

你好我是java的新手,我是从Herbert Schildt Book中读到的。 所以我的第一个问题。

  1. 我想在上面的程序中知道,print()方法会刷新流,因为println()在结束换行符后刷新。
  2. System.out.write();方法是否会刷新流? 请具体。

2 个答案:

答案 0 :(得分:2)

是的,System.out.printSystem.out.write都会刷新流。

编辑:如果输入字符串包含换行符,则只会刷新流。)

如果您从PrintStream.java查看java.io的源代码,可以看到来源:

private void write(char buf[]) {
    try {
        synchronized (this) {
            ensureOpen();
            textOut.write(buf);
            textOut.flushBuffer();
            charOut.flushBuffer();
            if (autoFlush) {
                for (int i = 0; i < buf.length; i++)
                    if (buf[i] == '\n')
                        out.flush();
            }
        }
    }
    catch (InterruptedIOException x) {
        Thread.currentThread().interrupt();
    }
    catch (IOException x) {
        trouble = true;
    }
}

答案 1 :(得分:1)

来自java docs

Println()通过写行分隔符字符串来终止当前行。行分隔符字符串由系统属性line.separator定义,不一定是单个换行符(&#39; \ n&#39;)。

println(String)打印一个字符串,然后终止该行。此方法的行为就像调用print(String)然后调用println()。

print() 打印一个对象。 String.valueOf(Object)方法生成的字符串根据平台的默认字符编码转换为字节,这些字节的写入方式与write(int)方法完全相同。

write() 将指定的字节写入此流。如果该字节是换行符并且启用了自动刷新,则将调用flush方法。 注意,字节写为给定;要编写将根据平台的默认字符编码进行翻译的字符,请使用print(char)或println(char)方法。

修改: - 错过了添加一个imp行Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

创建启用了autoflush的打印流对象out = new PrintWriter(.getOutputStream(), true ) ;

相关问题