现在的位置: 首页 > 综合 > 正文

System.out.write和System.out.println

2018年05月07日 ⁄ 综合 ⁄ 共 2303字 ⁄ 字号 评论关闭

问题:

System.out.write是字节流,System.out.println一个是字符流
先说System.out.write
class A
{
public static void main(String[] args)
{
char a='a';
System.out.write(a);
}
}在控制台什么都看不到,但是
class A
{
public static void main(String[] args)
{
char a='a';
System.out.write(a);
System.out.write('\n');
}
}这样为什么能在控制台输出a来
哪位高手给我解释下
再说下System.out.println
class A
{
public static void main(String[] args)
{
char a='a';
System.out.println('a');
}
}在控制台上输出的是a
class A
{
public static void main(String[] args)
{
char a='a';
System.out.write(a);
}
}在控制台上输出的是97

 

 

推荐答案:

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();
     }
}
catch (InterruptedIOException x) {
     Thread.currentThread().interrupt();
}
catch (IOException x) {
     trouble = true;
}
    }
newLine()会刷新out。

System.out.write(a); 调用的是PrintStream.write(int b)方法
write(int b) 的源代码如下:
public void write(int b) {
try {
     synchronized (this) {
  ensureOpen();
  out.write(b);
  if ((b == '\n') && autoFlush)
      out.flush();
     }
}
catch (InterruptedIOException x) {
     Thread.currentThread().interrupt();
}
catch (IOException x) {
     trouble = true;
}
    }

看过源代码后应该明白两者之间的差异了,println(String s)不但会刷新out,而且还会同时刷新textOut和charOut,而write(int b)只有当b == '\n'时才刷新out。这也是为什么加了System.out.write('\n'); 后就能显示出来了,问题就在于out没有刷新。

楼主的第二个问题很好解释,因为在print(String s)中,会刷新textOut和charOut。
textOut和charOut是什么?看一下PrintStream中的定义:
private BufferedWriter textOut;
    private OutputStreamWriter charOut;

textOut和charOut在init(OutputStreamWriter osw)方法中初始化,init(OutputStreamWriter osw)的代码如下:
private void init(OutputStreamWriter osw) {
this.charOut = osw;
this.textOut = new BufferedWriter(osw);

抱歉!评论已关闭.