一、Apache commons-io(开发神器)
1. 引入依赖
1 2 3 4 5 6
| <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");
FileUtils.copyFile(src, dest);
String content = FileUtils.readFileToString(src, StandardCharsets.UTF_8);
FileUtils.writeStringToFile(dest, "写入内容", StandardCharsets.UTF_8);
FileUtils.copyDirectory(new File("dir1"), new File("dir2"));
IOUtils.closeQuietly(new FileInputStream(src)); } }
|
优势
- 极简代码,告别手动循环读写、手动关流
- 自带递归目录、文件过滤、文件大小统计
- 生产项目普遍引入,减少重复 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 对比
- File 方法少、报错模糊、删除 / 遍历容易出问题
- NIO.2
Files 支持:文件属性、软连接、权限、快速遍历
- 新项目优先用 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(); }
|