首页 > 编程语言 >【Java基础】System.out.println() 解析

【Java基础】System.out.println() 解析

时间:2022-09-20 16:34:10浏览次数:54  
标签:Java PrintStream void System catch println public out

1.代码说明
image
System类提供一些有用的属性和方法,包括标准输入输出和错误打印。
有一个对象属性out,类型为PrintStream。
setOut()方法使用static修饰,类加载时执行。
该对象属性可以调用PrintStream类中的打印方法。

public final class System {

    public final static PrintStream out = null;

    public static void setOut(PrintStream out) {
        checkIO();
        setOut0(out);
    }
}

public class PrintStream extends FilterOutputStream
    implements Appendable, Closeable
{
    public void println(String x) {
        synchronized (this) {
            print(x);
            newLine();  //换行
        }
    }

    public void print(String s) {
        if (s == null) {
            s = "null";
        }
        write(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;
        }
    }

    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;
        }
    }
}

PrintStream类中包含打印各种数据类型的重载方法。
image

标签:Java,PrintStream,void,System,catch,println,public,out
From: https://www.cnblogs.com/zhishu/p/16711532.html

相关文章