System.out的Print()vs Write()方法 [英] Print() vs Write() method of System.out

查看:199
本文介绍了System.out的Print()vs Write()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PrintStream的Javadoc #print(char)状态

打印一个字符.字符被翻译成一个或多个字节 根据平台的默认字符编码,这些 字节完全以write(int)方法的方式写入.

Prints a character. The character is translated into one or more bytes according to the platform's default character encoding, and these bytes are written in exactly the manner of the write(int) method.

因此,这意味着以下代码应打印2个'a',但是打印一个'a'而不是两个.

So this means that following code should print 2 'a' however prints one 'a' not two.

System.out.print('a');
System.out.write('a');

有人可以帮我理解这一行为吗

Can some one help me understand this behaviour

推荐答案

按照

将指定的字节写入此流.如果字节是换行符,并且 启用自动刷新后,将调用flush方法.

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.

所以只需拨打flush.

System.out.write('a');之后拨打System.out.flush();.

或者

根据文档建议,将输出流设置为autoflushable,然后在程序末尾写一个新行char.实际上,如果您查看源代码

As the docs suggest, set the output stream to autoflushable and then write a new line char at the end of your program. In fact the PrintStream object System.out is already set to autoflushable if you look at the source code System class. So really, all you need to do is just print a new line character in the end. No need to call flush.

System.out.print('a');
System.out.write('a');
System.out.write('\n');

这篇关于System.out的Print()vs Write()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆