The java.io.Writer.flush() method flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination. Then, if that destination is another character or byte stream, flush it. Thus one flush() invocation will flush all the buffers in a chain of Writers and OutputStreams.
public class Demo {
public static void main(String[] ars) throws Exception {
System.out.println("hello");
PrintWriter writer = new PrintWriter(System.out);
writer.println("writer start");
// writer.flush();
try {
Thread.sleep();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
writer.println("writer close");
writer.close();
}
}
如上面代碼,如果flush()被注釋掉,則列印完“hello”之後3秒才會列印”writer start”,”writer close”,因為writer.close()在關閉輸出流前會調用一次flush()。效果如下:
如果flush()沒有被注釋掉,則則列印完“hello”之後會立即列印”writer start”。