您的位置:首页 > 编程语言 > Java开发

Java System

2016-03-30 17:08 381 查看

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。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: