2011-12-13 45 views
6

我寫一個簡單的函數是這樣的:改寫成一個文件

private static void write(String Swrite) throws IOException { 
    if(!file.exists()) { 
     file.createNewFile(); 
    } 
    FileOutputStream fop=new FileOutputStream(file); 
    if(Swrite!=null) 
     fop.write(Swrite.getBytes()); 
    fop.flush(); 
    fop.close(); 
} 

每次我叫它,它重寫,然後我剛拿到寫在最後的項目。我怎樣才能改變它不重寫?變量file全局定義爲File

回答

3

在您FileOutputStreamconstructor,你需要添加boolean append參數。然後,它看起來就像這樣:

FileOutputStream fop = new FileOutputStream(file, true); 

這告訴FileOutputStream,它應該將文件添加的不是清除和重寫其目前所有的數據。

+0

是的,這是正確的,謝謝 – seventeen

+0

,但仍然有點問題,它沒有任何空間,它寫在最後一個字符後,所以它不會被讀取,我怎麼能讓它在每次寫後給一個空間? – seventeen

+1

chang'fop.write(...)'到'fop.write(... +「\ n」)' – Jon

2

使用以作爲參數追加標誌的承包商。

FileOutputStream fop=new FileOutputStream(file, true); 
+0

,這是正確的,感謝 – seventeen

+0

但還是有點問題完成的,它沒有做任何的空間,最後一個字符寫入正是這樣它會不可讀,我怎麼能讓它在每次寫入後給出空間 – seventeen

+0

@MostafaAlli:然後**寫入空格 –

0

嘗試RandomAccessFile如果您嘗試寫入某些字節偏移量。

+1

它不一定是某個偏移量,他只是想要附加文件。 – Jon

0

拖參數構造函數是正確的。它是多餘的:

if(!file.exists()) { 
     file.createNewFile(); 
} 

構造函數將爲您做。

1

您應該在append模式下打開該文件,默認情況下FileOutputStreamwrite模式下打開文件。而且你也無需檢查的file存在,這將隱含地被FileOutputStream

private static void write(String Swrite) throws IOException { 
    FileOutputStream fop=new FileOutputStream(file, true); 
    if(Swrite!=null) 
     fop.write(Swrite.getBytes()); 
    fop.flush(); 
    fop.close(); 
}