2011-03-04 102 views
2

我遇到了这个程序,它没有按照预期的方式工作。Java字符串的奇怪行为

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,但它不打印任何东西。到底是怎么回事?有任何想法吗?提前致谢。

+9

你忘了'flush()'。 – 2011-03-04 21:01:32

回答

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; 
    } 
} 
+1

你是对的,但是你没有解决主要问题:为什么用print()打印的字符最终被刷新,而用write()打印的字符不能? – ChrisJ 2011-03-04 21:19:47

+0

@ChrisJ:你说的没错。我添加了更多信息。 – Jeremy 2011-03-04 21:30:10

+0

@Jeremy:你添加的东西是正确的,但是如果你看看代码,print(char)就会调用write(String),它具有与write(int)相同的行为。所以我仍然没有得到它... 然后Jonathon回答: @ChrisJ这应该是一个评论,但回答“为什么”:系统类初始化出来,像这样:new PrintStream(new BufferedOutputStream(fdOut ,128),真)。它将autoFlush设置为true。 – ChrisJ 2011-03-04 22:05:28