標準實現
import java.io.*;
import java.util.ArrayList;
public class ArrayListToFile {
public static void main(String[] args) throws IOException {
ArrayList<String> list = new ArrayList<>();
list.add("first");
list.add("second");
list.add("third");
File file = new File("d:/output.txt");
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (String line : list) {
bw.write(line);
bw.newLine(); // 跨平台換行
}
}
}
}
進階:泛型工具方法
public static <T> void writeList(List<T> list, File file, Function<T, String> mapper) throws IOException {
try (BufferedWriter bw = new BufferedWriter(new FileWriter(file))) {
for (T item : list) {
bw.write(mapper.apply(item));
bw.newLine();
}
}
}
// 調用
writeList(list, new File("out.txt"), Object::toString);
writeList(userList, new File("users.txt"), u -> u.getName() + "," + u.getEmail());
大文件優化
- 增大緩衝區:
new BufferedWriter(new FileWriter(file), 64 * 1024)。
- 異步寫入:
Files.writeAsync(path, lines, StandardOpenOption.CREATE) (Java 11+)。
- 分批 flush:每 1000 行
bw.flush(),平衡內存與磁盤 I/O。
編碼指定
// Java 10+
try (BufferedWriter bw = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) { ... }
// Java 8
try (BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"))) { ... }
常見錯誤
| 錯誤 | 原因 | 修正 |
| 中文亂碼 | 未指定 UTF-8,系統默認 GBK | 显式指定 StandardCharsets.UTF_8 |
| 文件被佔用 | 未關閉流 / 別的進程打開 | try-with-resources 自動關閉 |
| 最後一行無換行 | 忘記 bw.newLine() | 循環內統一調用 |