2012-05-27 51 views
0

清單我的程序片段如下FileOuputStream爲循環寫入字節,但沒有數據寫入?

public class InStream { 

    static FileOutputStream file=null; 
    static { 
     try { 
      file = new FileOutputStream("deo.txt"); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } 
    } 

    public static void main(String[] args) { 

     try { 
        //when i try to replace below infinite loop, 
        //it is also not able to output my String 
        //while(ture) 
         or 
        //for(;;) 

      for(int i=0;i<100000;i++){ 
       file.write("AB ".getBytes()); 
      } 

       //file.flush(); 

      file.close(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 

運行這個程序 - >打開deo.txt - >有這個文件中沒有數據

但是當我發表意見的for循環下面的代碼片段僅僅只有測試:

try { 
      file.write("AB ".getBytes()); 
      file.close(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

現在我可以看到文件中的「AB」字符串。很奇怪....

任何人都可以幫我一個忙嗎?

+0

你用*'file.flush();來試試*嗎? – Nivas

+0

正如我所知FileOutputStream沒有關於刷新的相關功能,如果你確實這樣做,它只調用其父母的空方法,不執行任何東西 – user917879

+0

好的。你使用的是哪個版本的java?在哪個操作系統?當我嘗試你的代碼時,我在文件中看到100000個「AB」。另外,當你使用'while(true)'這樣的無限循環時,你可能看不到字符串,因爲你永遠不會關閉流。 – Nivas

回答

0

代碼中沒有錯誤。必須生成包含AB AB的文件「deo.txt」...............

+0

我相信它不能輸出任何東西在我的工作區 – user917879

+0

但我在我的機器上執行你的程序它工作正常 –

+0

哦~~是當我打開它使用editplus,它確實包含我的輸出字符串,但是當我打開它時我的日食工作區,我找不到anythinh,哦〜忘記它,無論如何認爲您的意見。 – user917879

0

我測試了你的代碼。它的工作原理。但是對於deo.txt。你可以檢查它的大小,如果它是大約293k。如果使用Eclipse文本編輯器打開它,則不顯示任何內容。但您可以使用其他系統編輯器(如記事本++)查看它。