Java System

来源:互联网 发布:部队网络保密教育 编辑:程序博客网 时间:2024/06/04 23:21

System.out

System.out的类型为PrintStream;
System.out.println(‘a’);
实际上调用是PrintStream的println(char c)方法;
而println(char c)方法的源代码为:

public void println(String x) {    synchronized (this) {        print(x);        newLine();    }}

可见Println调用了print(char c)方法,print(char c)方法的源代码如下:

public void print(String s) {    if (s == null) {        s = "null";    }    write(s);}

可见调用的是write(String s)方法,write(String s)的代码为:

private void write(String s) {    try {        synchronized (this) {            ensureOpen();            textOut.write(s);            textOut.flushBuffer();            charOut.flushBuffer();            if (autoFlush && (s.indexOf('\n') >= 0))                out.flush();        }    }    catch (InterruptedIOException x) {        Thread.currentThread().interrupt();    }    catch (IOException x) {        trouble = true;    }}

当字符串中含有’\n’时会刷新out,此处的out是OutStream对象的实例。println(String s)最后调用newLine() 方法,newLine()的代码如下:

private void newLine() {    try {        synchronized (this) {            ensureOpen();            textOut.newLine();            textOut.flushBuffer();            charOut.flushBuffer();            if (autoFlush)                out.flush();        }    }    catch (InterruptedIOException x) {        Thread.currentThread().interrupt();    }    catch (IOException x) {        trouble = true;    }}

newLine()会刷新out。

0 0