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(3000);}catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}writer.println("writer close");writer.close();}}如上面代碼,如果flush()被註釋掉,則打印完“hello”之後3秒才會打印”writer start”,”writer close”,因為writer.close()在關閉輸出流前會調用一次flush()。效果如下:
如果flush()沒有被註釋掉,則則打印完“hello”之後會立即打印”writer start”。
總結
以上就是本文關於IO中flush()函數的使用代碼示例的全部內容,希望對大家有所幫助。感興趣的朋友可以繼續參閱本站其他相關專題,如有不足之處,歡迎留言指出。感謝朋友們對本站的支持!