javaIO高级工具与实战

一、Apache commons-io(开发神器)

1. 引入依赖

1
2
3
4
5
6
<!-- Maven -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.15.1</version>
</dependency>

2. 核心两大工具类

  • FileUtils:文件 / 目录操作
  • IOUtils:流操作、关闭、拷贝

3. 常用高频 API

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
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class CommonsIoDemo {
public static void main(String[] args) throws IOException {
File src = new File("src.txt");
File dest = new File("copy.txt");

// 1. 复制文件
FileUtils.copyFile(src, dest);

// 2. 读取文件为字符串
String content = FileUtils.readFileToString(src, StandardCharsets.UTF_8);

// 3. 写入字符串到文件
FileUtils.writeStringToFile(dest, "写入内容", StandardCharsets.UTF_8);

// 4. 递归复制整个文件夹
FileUtils.copyDirectory(new File("dir1"), new File("dir2"));

// 5. 一键关闭流(不用try-with-resources时兜底)
IOUtils.closeQuietly(new FileInputStream(src));
}
}

优势

  1. 极简代码,告别手动循环读写、手动关流
  2. 自带递归目录、文件过滤、文件大小统计
  3. 生产项目普遍引入,减少重复 IO 工具类手写

二、NIO.2 | JDK7 全新文件 API(Path / Paths / Files)

设计定位

  • 替代老旧 File 类,方法更丰富、异常更清晰、链式操作
  • 纯 JDK 原生,无需第三方依赖
  • 静态工具类 Files 提供全部文件读写、复制、删除、遍历

1. 基础对象

  • Path:替代 File,代表文件 / 目录路径
  • Paths:静态创建 Path
  • Files:静态工具类,所有文件操作

2. 常用实战代码

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
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;

public class NIO2Demo {
public static void main(String[] args) throws Exception {
Path src = Paths.get("test.txt");
Path copy = Paths.get("copy.txt");

// 读取全部文本
List<String> lines = Files.readAllLines(src);
// 单行读取字节
byte[] bytes = Files.readAllBytes(src);

// 写入文件
Files.write(copy, "NIO2写入测试".getBytes());

// 文件复制
Files.copy(src, copy);

// 创建目录
Files.createDirectories(Paths.get("a/b/c"));

// 判断是否存在
boolean exists = Files.exists(src);
}
}

File 与 NIO.2 对比

  1. File 方法少、报错模糊、删除 / 遍历容易出问题
  2. NIO.2 Files 支持:文件属性、软连接、权限、快速遍历
  3. 新项目优先用 Path + Files

三、经典 IO 实战案例(必练)

案例 1:文件夹递归拷贝(纯 JDK 原生)

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
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class DirCopy {
public static void copyDir(File srcDir, File destDir) throws IOException {
// 目标目录不存在则创建
if (!destDir.exists()) {
destDir.mkdirs();
}
File[] files = srcDir.listFiles();
if (files == null) return;

for (File file : files) {
if (file.isDirectory()) {
// 递归拷贝子目录
copyDir(file, new File(destDir, file.getName()));
} else {
// 拷贝单个文件
try (FileInputStream fis = new FileInputStream(file);
FileOutputStream fos = new FileOutputStream(new File(destDir, file.getName()))) {
byte[] buf = new byte[1024];
int len;
while ((len = fis.read(buf)) != -1) {
fos.write(buf, 0, len);
}
}
}
}
}
}

案例 2:大文件分片读取(防止 OOM)

核心思想:

不一次性加载全文件,固定缓冲区分段读取,避免内存溢出

1
2
3
4
5
6
7
try (BufferedReader br = new BufferedReader(new FileReader("big.log"))) {
String line;
// 按行分片处理,无论文件多大,内存只存一行
while ((line = br.readLine()) != null) {
handleLine(line);
}
}

案例 3:配置文件 / 日志写入标准模板

1
2
3
4
5
6
// 追加写入日志,不覆盖
try (FileWriter writer = new FileWriter("app.log", true);
BufferedWriter bw = new BufferedWriter(writer)) {
bw.write("[" + System.currentTimeMillis() + "] 系统运行日志");
bw.newLine();
}

javaIO高级工具与实战
http://hanqichuan.com/2026/04/20/java的IO/javaIO高级工具与实战/
作者
韩启川
发布于
2026年4月20日
许可协议