[英]Strange behavior of Java String
I came across this program and its not behaving in expected way. 我遇到了这个程序,它没有按照预期的方式运行。
public class StringTest
{
public static void main(String[] args)
{
String s = "Hello world";
for(int i = 0 ; i < s.length() ; i++)
{
System.out.write(s.charAt(i));
}
}
}
If we think it should print Hello world but it prints nothing. 如果我们认为它应该打印Hello world但它什么都不打印。 What is going on?
到底是怎么回事? Any ideas?
有任何想法吗? Thanks in advance.
提前致谢。
You want: System.out.print(s.charAt(i));
你想要:
System.out.print(s.charAt(i));
As per the API of write
: 根据
write
的API :
Note that the byte is written as given;
注意,字节写为给定; to write a character that will be translated according to the platform's default character encoding, use the print(char) or println(char) methods.
要编写将根据平台的默认字符编码进行翻译的字符,请使用print(char)或println(char)方法。
As noted in a comment to your question, if you really wish to use write()
you need to flush()
. 如您对问题的评论中所述,如果您真的希望使用
write()
,则需要flush()
。
The reason why write(int)
doesn't print anything is because it only flushes the stream on \\n
and when autoFlush
is true. write(int)
不打印任何内容的原因是因为它只刷新\\n
和autoFlush
为true时的流。
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.