2011年6月23日 星期四

java io的flush

舉凡使用java做io時
必須要使用flush()
才能將資料輸出到輸出裝置
輸出裝置可能是: 螢幕或檔案等...

以下這個範例
FileWriter要寫出一個String
但是十秒後才會flush
所以執行時
你會看到先建立sample.txt
但是打開一看
裡面空無一物
過了十秒後
再次打開sample.txt
會發現裡面多了一行Today is a good day

import java.io.*;
import java.util.*;

public class Test_IO{

 public static void main(String args[]){
  try{
   String content= "Today is a good day.";
   FileWriter fo = new FileWriter("sample.txt");     
   fo.write(content);

   long curr = System.currentTimeMillis();
   while(true){
   long result = System.currentTimeMillis()-curr;
    if(result/10000 == 1){
     //10秒後flush
     fo.flush();
     System.out.println("Flushed!");    
     break;
    }
   }
   fo.close();  
  }catch(Exception e){
   e.printStackTrace();
  }
 }//end main
}//end class


你或許會問
常常用的System.out.println()
也是個io輸出
為什麼不用打System.out.flush()
就可以直接看到結果

這是因為有些io類可以設定auto flush(自動)
System的out是個PrintStrem物件
在api說明中有寫道:

Optionally, a PrintStream can be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

所以上完廁所
如果沒有自動沖水裝置
別忘了要自己手動沖水(flush!)

沒有留言:

張貼留言