System.out.write和System.out.printlnSystem.out.writ

发布时间:2021-02-20 01:16:04

System.out.write和System.out.printlnSystem.out.write是字节流,System.out.println一个是字符流先说System.out.writeclass A{public static void main(String[] args){char a='a';System.out.write(a);}}在控制台什么都看不到,但是class A{p

网友回答

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(char c) {
write(String.valueOf(c));
}可见调用的是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();
}}
以上问题属网友观点,不代表本站立场,仅供参考!