简体   繁体   English

Java中的outputstream出乎意料的结果

[英]Unexpected result with outputstream in Java

I am trying out a simple program for printing characters. 我正在尝试一个简单的程序来打印字符。 When I do this: 当我这样做:

import java.io.*;

public class listit {

  public static void main(String[] args) {

    for (int i = 32; i < 127; i++) {
      System.out.write(i);
      // break line after every eight characters.
      if (i % 8 == 7) System.out.write('\n');
      else System.out.write('\t');
    }
    System.out.write('\n');
   }
} 

I am getting the expected result, that is, the printable subset of the ASCII character set is being printed out. 我得到了预期的结果,即打印出ASCII字符集的可打印子集。 However, when I try something similar: 但是,当我尝试类似的东西时:

import java.io.*;
public class listit {
public static void main(String[] args) {
int i = 122;
System.out.write(i);
}
}

I am getting no output at all, while I was expecting z . 我完全没有输出,而我期待z How is this program different from the one above, save the absence of a loop? 如果没有循环,这个程序与上面的程序有什么不同?

PrintStream supports auto-flushing or flushing on a newline. PrintStream支持在换行符上自动刷新或刷新。

System.out has auto-flushing enabled but for System.out.write('A') it will only auto-flush if you write a newline. System.out已启用自动刷新,但对于System.out.write('A'),它只会在您写入换行符时自动刷新。 Note: if you do System.out.write("A".getByte()) will auto-flush. 注意:如果您执行System.out.write(“A”.getByte())将自动刷新。

The Javadoc for PrintStream.write(int) states PrintStream.write(int)的Javadoc说明

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方法。

This means you need auto-flush AND write a newline. 这意味着您需要自动刷新并写入换行符。

Note: PrintStream.print(char) states 注意:PrintStream.print(char)状态

these bytes are written in exactly the manner of the write(int) method. 这些字节的写入方式与write(int)方法完全相同。

This doesn't make it clear that the flushing is different. 这并不清楚冲洗是不同的。 It will flush if you have auto-flush OR write a new line. 如果您有自动刷新或写入新行,它将刷新。

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

prints just 只打印

a

I suspect this inconsistency is a long standing bug rather than a feature (in other words it won't be fixed). 我怀疑这种不一致是一个长期存在的错误,而不是一个功能(换句话说,它不会被修复)。 ;) ;)

This means you have to either 这意味着你必须要么

System.out.flush();

or 要么

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

to see the last line. 看到最后一行。

Possibly, writing a new line \\n flushes the stream. 可能,写一个新行\\n刷新流。

in 2nd programs, you're not printing a newline and the contents are not flushed from stream. 在第二个程序中,您不打印换行符,并且内容不会从流中刷新。 so you see no output. 所以你看不到输出。

See: When/why to call System.out.flush() in Java 请参阅: 何时/为何在Java中调用System.out.flush()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM