Java String的奇怪行为

Ume*_*cha 2 java string

我遇到了这个程序,它没有按照预期的方式运行.

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));
           }
      }
}  
Run Code Online (Sandbox Code Playgroud)

如果我们认为它应该打印Hello world但它什么都不打印.到底是怎么回事?有任何想法吗?提前致谢.

Jer*_*emy 12

你要: System.out.print(s.charAt(i));

按照该APIwrite:

注意,字节写为给定; 要编写将根据平台的默认字符编码进行翻译的字符,请使用print(char)或println(char)方法.

如您对问题的评论中所述,如果您真的希望使用write(),则需要flush().


之所以write(int)不打印任何东西,是因为它只刷新了流\n,什么时候才autoFlush真实.

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;
    }
}
Run Code Online (Sandbox Code Playgroud)