简体   繁体   中英

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. 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 . How is this program different from the one above, save the absence of a loop?

PrintStream supports auto-flushing or flushing on a newline.

System.out has auto-flushing enabled but for System.out.write('A') it will only auto-flush if you write a newline. Note: if you do System.out.write("A".getByte()) will auto-flush.

The Javadoc for PrintStream.write(int) states

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.

This means you need auto-flush AND write a newline.

Note: PrintStream.print(char) states

these bytes are written in exactly the manner of the write(int) method.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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