2011-12-17 129 views
61

如果您使用FileOutputStream方法,每次通過這種方法編寫文件時,都會丟失舊數據。是否可以通過FileOutputStream寫入文件而不丟失舊數據?如何使用FileOutputStream寫入數據而不丟失舊數據?

+1

如果你想知道你怎麼能工作這爲你自己,你可以讀Javadoc。 http://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html – 2011-12-17 16:21:13

+0

[OutputStreamWriter代替FileOutputStream中] [1] [1]:HTTP:/ /stackoverflow.com/questions/23320070/appending-a-string-to-an-existing-file-using-outputstreamwriter/23320195?noredirect=1#comment35707473_23320195 – sourabh 2014-04-27 10:41:48

+1

@PeterLawrey通過我們自己學習,通常只需問互聯網。而且是java doc之前的第一個結果:-) – 2017-12-30 22:12:16

回答

114

,需要使用帶有Fileboolean

FileOutputStream(File file, boolean append) 

和布爾值設置爲true構造。這樣,你寫的數據將被追加到文件的末尾,而不是覆蓋已經存在的內容。

18

使用的構造材料附加到文件:

FileOutputStream(File file, boolean append) 
Creates a file output stream to write to the file represented by the specified File object. 

所以要追加到一個文件說「的abc.txt」使用

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);