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 
" ; //字符串末尾需要换行符
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!
"); //字符串末尾需要换行符   
37           rf.close();//关闭文件流   
38          }catch (IOException e){   
39              e.printStackTrace();   
40          }   
41            
42            
43      }   
44   
45 }
原文地址:https://www.cnblogs.com/blog-zuo/p/4826357.html