正题:追加内容到文件末尾的几种常用方法

主题:追加内容到文件末尾的几种常用方法
1.import java.io.BufferedWriter;  
2.import java.io.FileOutputStream;  
3.import java.io.FileWriter;  
4.import java.io.IOException;  
5.import java.io.OutputStreamWriter;  
6.import java.io.RandomAccessFile;  
7. 
8./** 
9. * 描述:追加内容到文件末尾 
10. * @author Administrator 
11. * 
12. */ 
13.public class WriteStreamAppend {  
14.    /** 
15.     * 追加文件:使用FileOutputStream,在构造FileOutputStream时,把第二个参数设为true 
16.     *  
17.     * @param fileName 
18.     * @param content 
19.     */ 
20.    public static void method1(String file, String conent) {  
21.        BufferedWriter out = null;  
22.        try {  
23.            out = new BufferedWriter(new OutputStreamWriter(  
24.                    new FileOutputStream(file, true)));  
25.            out.write(conent);  
26.        } catch (Exception e) {  
27.            e.printStackTrace();  
28.        } finally {  
29.            try {  
30.                out.close();  
31.            } catch (IOException e) {  
32.                e.printStackTrace();  
33.            }  
34.        }  
35.    }  
36. 
37.    /** 
38.     * 追加文件:使用FileWriter 
39.     *  
40.     * @param fileName 
41.     * @param content 
42.     */ 
43.    public static void method2(String fileName, String content) {  
44.        try {  
45.            // 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件  
46.            FileWriter writer = new FileWriter(fileName, true);  
47.            writer.write(content);  
48.            writer.close();  
49.        } catch (IOException e) {  
50.            e.printStackTrace();  
51.        }  
52.    }  
53. 
54.    /** 
55.     * 追加文件:使用RandomAccessFile 
56.     *  
57.     * @param fileName 
58.     *            文件名 
59.     * @param content 
60.     *            追加的内容 
61.     */ 
62.    public static void method3(String fileName, String content) {  
63.        try {  
64.            // 打开一个随机访问文件流,按读写方式  
65.            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");  
66.            // 文件长度,字节数  
67.            long fileLength = randomFile.length();  
68.            // 将写文件指针移到文件尾。  
69.            randomFile.seek(fileLength);  
70.            randomFile.writeBytes(content);  
71.            randomFile.close();  
72.        } catch (IOException e) {  
73.            e.printStackTrace();  
74.        }  
75.    }  
76. 
77.    public static void main(String[] args) {  
78.        System.out.println("start");  
79.        method1("c:/test.txt", "追加到文件的末尾");  
80.        System.out.println("end");  
81.    }  
82. 
83.}