本文實例講述了java實現追加內容到文件末尾的常用方法。分享給大家供大家參考,具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
import java.io.BufferedWriter; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; public class WriteStreamAppend { /** * 追加文件:使用FileOutputStream,在構造FileOutputStream時,把第二個參數設為true * * @param fileName * @param content */ public static void method1(String file, String conent) { BufferedWriter out = null ; try { out = new BufferedWriter( new OutputStreamWriter( new FileOutputStream(file, true ))); out.write(conent); } catch (Exception e) { e.printStackTrace(); } finally { try { out.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 追加文件:使用FileWriter * * @param fileName * @param content */ public static void method2(String fileName, String content) { try { // 打開一個寫文件器,構造函數中的第二個參數true表示以追加形式寫文件 FileWriter writer = new FileWriter(fileName, true ); writer.write(content); writer.close(); } catch (IOException e) { e.printStackTrace(); } } /** * 追加文件:使用RandomAccessFile * * @param fileName * 文件名 * @param content * 追加的內容 */ public static void method3(String fileName, String content) { try { // 打開一個隨機訪問文件流,按讀寫方式 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw" ); // 文件長度,字節數 long fileLength = randomFile.length(); // 將寫文件指針移到文件尾。 randomFile.seek(fileLength); randomFile.writeBytes(content); randomFile.close(); } catch (IOException e) { e.printStackTrace(); } } public static void main(String[] args) { System.out.println( "start" ); method1( "c:/test.txt" , "追加到文件的末尾" ); System.out.println( "end" ); } |
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/jsjwk/article/details/3942167