在文件末尾進行內容的追加,有三種方法:
1
public class FileAppendTest {
2
/**
3
* 利用FileoutStream構造方法的每二個參數實現內容的追加
4
* @param f 文件
5
* @param context 所要追加的內容
6
*/
7
public static void append01(File f,String context) throws Exception{
8
BufferedWriter br = new BufferedWriter(new OutputStreamWriter
9
(new FileOutputStream(f,true)));
10
br.write(context);
11
br.flush();
12
br.close();
13
}
14
/**
15
* 利用FileWriter構造方法中的第二個參數實現內容的追加
16
* @param f 文件
17
* @param context 內容
18
*/
19
public static void append02(File f,String context)throws Exception{
20
FileWriter fw = new FileWriter(f, true);
21
fw.write(context);
22
fw.flush();
23
fw.close();
24
}
25
/**
26
* 利用RandomAccessFile的seek()方法,
27
* 將寫文件指針移至文件末尾,實現內容的追加
28
* @param f 文件
29
* @param context 內容
30
*/
31
public static void append03(File f,String context)throws Exception{
32
RandomAccessFile raf = new RandomAccessFile(f, "rw");
33
raf.seek(raf.length());//將寫文件指針移至文件末尾
34
raf.writeBytes(context);
35
raf.close();
36
}
37
}

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
