FileOutputStream

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
package com.ledao;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
* @author LeDao
* @company
* @create 2022-04-02 7:29
*/
public class Test {

public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\LeDao\\Desktop\\1.txt");
FileOutputStream fileOutputStream = new FileOutputStream(file, true);
for (int i = 1; i <= 10; i++) {
//追加内容后换行
String content = "内容" + i + "\r\n";
//追加内容后不换行
//String content = "内容" + i;
fileOutputStream.write(content.getBytes());
}
fileOutputStream.close();
}
}

FileWriter

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
package com.ledao;

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

/**
* @author LeDao
* @company
* @create 2022-04-02 7:29
*/
public class Test {

public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\LeDao\\Desktop\\1.txt");
FileWriter fileWriter = new FileWriter(file, true);
for (int i = 1; i <= 10; i++) {
//追加内容后换行
String content = "内容" + i + "\r\n";
//追加内容后不换行
//String content = "内容" + i;
fileWriter.write(content);
}
fileWriter.close();
}
}

RandomAccessFile

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
package com.ledao;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;

/**
* @author LeDao
* @company
* @create 2022-04-02 7:29
*/
public class Test {

public static void main(String[] args) throws IOException {
File file = new File("C:\\Users\\LeDao\\Desktop\\1.txt");
RandomAccessFile randomAccessFile = new RandomAccessFile(file, "rw");
long length = randomAccessFile.length();
randomAccessFile.seek(length);
for (int i = 1; i <= 10; i++) {
//追加内容后换行
//String content = "内容" + i + "\r\n";
//追加内容后不换行
String content = "内容" + i;
randomAccessFile.write(content.getBytes());
}
randomAccessFile.close();
}
}

使用Hutool

引入依赖

1
2
3
4
5
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.8.0.M2</version>
</dependency>

Java代码

下面这段代码追加的内容是换行的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.ledao;

import cn.hutool.core.io.file.FileAppender;

import java.io.File;

/**
* @author LeDao
* @company
* @create 2022-04-02 7:29
*/
public class Test {

public static void main(String[] args) {
File file = new File("C:\\Users\\LeDao\\Desktop\\1.txt");
FileAppender fileAppender = new FileAppender(file, 16, true);
for (int i = 1; i <= 10; i++) {
String content = "内容" + i;
fileAppender.append(content);
}
fileAppender.flush();
}
}