Java文件末尾追加字符串

Java進行文件輸出時,有時候想直接向已有文件末尾追加字符,而不是從頭開始寫,能夠採用如下三種方式實現:java

 1 package test;      
 2 import java.io.File;   
 3 import java.io.FileOutputStream;   
 4 import java.io.FileWriter;   
 5 import java.io.IOException;   
 6 import java.io.PrintWriter;   
 7 import java.io.RandomAccessFile;   
 8   
 9 public class FileRW {   
10     public static void main(String[] a)   {   
11         //方式一:
12         try {   
13              FileOutputStream fos = new FileOutputStream (new File("d:\\abc.txt"),true ) ;   
14              String str = "ABC \n" ; //字符串末尾須要換行符
15              fos.write(str.getBytes()) ;   
16              fos.close ();   
17          } catch (IOException e) {   
18              e.printStackTrace();   
19          }   
20            
21         //方式二:
22         try {   
23              FileWriter fw = new FileWriter("d:\\abc.txt",true);   
24              PrintWriter pw=new PrintWriter(fw);   
25              pw.println("append content");   //字符串末尾不須要換行符
26              pw.close () ;   
27              fw.close () ;   
28          } catch (IOException e) {   
29              e.printStackTrace();   
30          }   
31         
32         //方式三:   
33         try {   
34           RandomAccessFile rf=new RandomAccessFile("d:\\abc.txt","rw");   
35           rf.seek(rf.length());  //將指針移動到文件末尾   
36           rf.writeBytes("Append a line again!\n"); //字符串末尾須要換行符   
37           rf.close();//關閉文件流   
38          }catch (IOException e){   
39              e.printStackTrace();   
40          }   
41            
42            
43      }   
44   
45 }
相關文章
相關標籤/搜索