本例以Windows, JDK1.7 为基础,来演示对文件内容的追加,采用的类主要是FileWriter(file,true)来完成。
首先通过write()方法来对文件的写入,接着使用writeAppend()方法来对文件内容的追加。
实例代码如下:
FileWriteAppend.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
package com.devnp.io;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class FileWriteAppend {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub

write();

writeAppend();
}

public static void write() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));

String str = "Hi, Hello, I'm devnp.com" ;

bufferedWriter.write(str); //写入str

bufferedWriter.close();
}

public static void writeAppend() throws IOException{
File file = new File("D:\\Person-Test\\1.txt");

BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file, true));

String str = "Hi, Hello, I'm devnp.com too" ;

bufferedWriter.write(str); //写入str

bufferedWriter.close();
}

}

测试结果:
文件生成地址:D:\Person-Test\1.txt
内容:

Hi, Hello, I'm devnp.comHi, Hello, I'm devnp.com too