向文件尾加入內容有多種方法,常見的方法有兩種:
RandomAccessFile類可以實現隨機訪問文件的功能,可以以讀寫方式打開文件夾的輸出流
public void seek(long pos)可以將讀寫指針移到文件尾,參數Pos表示從文件開頭以字節為單位測量的偏移位置,在該位置文件指針。
public void write(int pos)將數據寫到讀寫指針后面,完成文件的追加。參數pos表示要寫入的Byte
通過FileWrite打開文件輸出流,構造FileWrite時指定寫入模式,是一個布爾量,為真時表示寫入的內容添加到已有文件的內容的后面,為假時表示重新寫文件,以前的記錄被清空,默認的值為假。
具體的例子可以參看以下的代碼:
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
73
74
75
76
77
78
79
80
81
82
|
package Characters; import Java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.RandomAccessFile; public class CharactersDemo_03 { // 使用RandomAccessFile實現文件的追加,其中:fileName表示文件名;content表示要追加的內容 public static void appendMethod_one(String fileName, String content) { try { // 按讀寫方式創建一個隨機訪問文件流 RandomAccessFile raf = new RandomAccessFile(fileName, "rw" ); long fileLength = raf.length(); // 獲取文件的長度即字節數 // 將寫文件指針移到文件尾。 raf.seek(fileLength); // 按字節的形式將內容寫到隨機訪問文件流中 raf.writeBytes(content); // 關閉流 raf.close(); } catch (IOException e) { e.printStackTrace(); } } // 使用FileWriter實現文件的追加,其中:fileName表示文件名;content表示要追加的內容 public static void appendMethod_two(String fileName, String content) { try { // 創建一個FileWriter對象,其中boolean型參數則表示是否以追加形式寫文件 FileWriter fw = new FileWriter(fileName, true ); // 追加內容 fw.write(content); // 關閉文件輸出流 fw.close(); } catch (IOException e) { e.printStackTrace(); } } public static void showFileContent(String fileName) { File file = new File(fileName); BufferedReader reader = null ; try { System.out.println( "以行為單位讀取文件內容,一次讀一整行:" ); reader = new BufferedReader( new FileReader(file)); String tempString = null ; int line = 1 ; // 一次讀入一行,直到讀入null為文件結束 while ((tempString = reader.readLine()) != null ) { // 顯示行號 System.out.println(line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null ) { try { reader.close(); } catch (IOException e1) { } } } } public static void main(String[] args) { String fileName = "C:/temp/append.txt" ; String content = "Successful operation!" ; System.out.println(fileName + "文件的內容如下:" ); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 // 按RandomAccessFile的形式追加文件 System.out.println( "\n按RandomAccessFile的形式追加文件后的內容如下:" ); CharactersDemo_03.appendMethod_one(fileName, content); CharactersDemo_03.appendMethod_one(fileName, "\n Game is Over! \n" ); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 // 按FileWriter的形式追加文件 System.out.println( "\n按FileWriter的形式追加文件后的內容如下:" ); CharactersDemo_03.appendMethod_two(fileName, content); CharactersDemo_03.appendMethod_two(fileName, "\n Game is Over! \n" ); CharactersDemo_03.showFileContent(fileName); // 顯示文件內容 } } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
原文鏈接:http://blog.csdn.net/zeng622peng/article/details/47781699