整理了下网上的资料,数据追加写入txt文件有三种方式,见下面代码:
方法一:
1 public void method1() {
2 FileWriter fw = null;
3 try {
4 //如果文件存在,则追加内容;如果文件不存在,则创建文件
5 File f=new File("E:\\dd.txt");
6 fw = new FileWriter(f, true);
7 } catch (IOException e) {
8 e.printStackTrace();
9 }
10 PrintWriter pw = new PrintWriter(fw);
11 pw.println("追加内容");
12 pw.flush();
13 try {
14 fw.flush();
15 pw.close();
16 fw.close();
17 } catch (IOException e) {
18 e.printStackTrace();
19 }
20 }
方法二:
1 public static void method2(String file, String conent) {
2 BufferedWriter out = null;
3 try {
4 out = new BufferedWriter(new OutputStreamWriter(
5 new FileOutputStream(file, true)));
6 out.write(conent+"\r\n");
7 } catch (Exception e) {
8 e.printStackTrace();
9 } finally {
10 try {
11 out.close();
12 } catch (IOException e) {
13 e.printStackTrace();
14 }
15 }
16 }
方法三:
1 public static void method3(String fileName, String content) {
2 try {
3 // 打开一个随机访问文件流,按读写方式
4 RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
5 // 文件长度,字节数
6 long fileLength = randomFile.length();
7 // 将写文件指针移到文件尾。
8 randomFile.seek(fileLength);
9 randomFile.writeBytes(content+"\r\n");
10 randomFile.close();
11 } catch (IOException e) {
12 e.printStackTrace();
13 }
14 }
15 }