Java String的奇怪行为

时间:2011-03-04 20:57:03

标签: 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));
           }
      }
}  

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

1 个答案:

答案 0 :(得分:12)

您想:System.out.print(s.charAt(i));

根据write的{​​{3}}:

  

请注意,该字节写为给定;要编写将根据平台的默认字符编码进行翻译的字符,请使用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;
    }
}
相关问题