java systemoutprint,Java的System.out.print()会永远缓冲到println()吗?

I overheard an argument about System.out.print() today. One person claimed that since print() doesn't including the terminating \n, the buffer it writes to will eventually fill up and start losing data. The other person claimed that they had been using System.out.print() for all their Java programs and had never run into this issue.

Is the first person right? Is it possible for System.out.print() to start blocking or dropping data if stdout is full? Is there an example of code that will cause this?

解决方案

When the buffer used by System.out.print fills up, the output is written into the file (or terminal or other data target that is connected to the program's standard output stream), resulting in an empty buffer. Writing output without caring about the buffer size is normal usage. You will never crash or block your program or lose data from not calling flush.

You only need to call flush explicitly if you need to make the data available outside your program immediately. For example, if your program is exchanging data back and forth with another program, and you're sending a request to that program and will wait for that program's reply, you need to call flush after sending your request to ensure that the other program receives it. Similarly, if your program (or the machine it runs on) crashes, only the output up to the last time you called flush is guaranteed to have been written out.

If the stream is set to flush automatically, then writing a newline character (explicitly or through println) is as good as calling flush. Calling close also calls flush (that's why close can throw an IOException: it might have to write data out and not be able to, e.g. because the stream is connected to a file on a full disk).

Note that flushing the buffer may cause the program to block, if the stream that System.out is connected to is not immediately ready to receive the data (e.g. when the data is piped to another program that doesn't read its input immediately). Since the buffer can be flushed at any time (because the buffer happens to be full), any call to print with a non-empty argument is potentially blocking.

For more information, see the buffered streams tutorial and the documentation of the java.io.PrintStream class.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值