简体   繁体   中英

System.out .write() executes but doesn't print

public class BRRead {
  public static void main(String[] args)   {
    int b;
    b='A';
    System.out .write(b);
    System.out .write('\n');
   }    
}

So when i execute the above program i get the expected output - A but when comment out the last line System.out.write('\\n'); the program executes but doesn't print the output - A. Can any one explain what's exactly happening here?

public class BRRead {
  public static void main(String[] args)   {
    int b;
    b='A';
    System.out .write(b);
    //System.out .write('\n');
  }        
}
public void write(int b)

Writes the specified byte to this stream. If the byte is a newline and automatic flushing is enabled then the flush method will be invoked.

In your example, flush() is not called automatically, if you call it explicitly the character will be printed.

在代码末尾调用System.out.flush()

From here

Basically, Java doesn't guarantee that output is actually sent to a file, socket, the screen, or any other output device until you call flush() on your OutputStream or Writer, or until it is closed. The OutputStream or Writer may buffer the output, meaning that it will be saved up and sent in larger chunks for efficiency. You can't really predict how this will be done.

PrintWriter.println() will automatically call flush(), by the way, although that doesn't matter here. But in any case, the general rule is that if you want output to appear somewhere immediately, and you're not using PrintWriter.println() (or PrintStream.println()), then call flush() yourself.

从 write(int bytevalue) 方法主体来看,arg 似乎是临时缓冲/存储的,并且在您写入新行之前实际上并未写入。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM