一、File类:文件系统操作核心
1. 核心功能概览
File file = new File("/data/test.txt");
boolean exists = file.exists();
boolean isDir = file.isDirectory();
long size = file.length();
long time = file.lastModified();
2. 文件系统操作示例
File dir = new File("/data/logs");
if (!dir.exists()) {
boolean success = dir.mkdirs();
System.out.println(success ? "创建成功" : "创建失败");
}
File src = new File("old.txt");
File dest = new File("/backup/new.txt");
if (src.exists()) {
boolean renamed = src.renameTo(dest);
}
File tempFile = new File("temp.tmp");
if (tempFile.exists()) {
boolean deleted = tempFile.delete();
}
3. 文件权限处理
file.setReadable(true);
file.setWritable(true);
if (!file.canRead()) {
throw new SecurityException("无读取权限");
}
二、字节流:InputStream/OutputStream
1. 文件打开与关闭机制

2. 字节流读取操作对比
方法签名 | 功能描述 | 适用场景 |
---|
int read() | 读取单个字节 | 极低频率读取 |
int read(byte[] b) | 读取到字节数组 | 常规批量读取 |
int read(byte[] b, int off, int len) | 读取到数组指定区间 | 分段处理大文件 |
3. 字节流写入操作对比
方法签名 | 功能描述 | 效率影响 |
---|
void write(int b) | 写入单个字节 | 极低(频繁IO) |
void write(byte[] b) | 写入整个字节数组 | 高(批量IO) |
void write(byte[] b, int off, int len) | 写入数组指定区间 | 中(可控写入) |
4. 最佳时间:使用try-with-resources自动关闭
try (InputStream in = new FileInputStream("source.dat");
OutputStream out = new FileOutputStream("backup.dat")) {
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = in.read(buffer)) != -1) {
out.write(buffer, 0, bytesRead);
}
} catch (IOException e) {
e.printStackTrace();
}
三、字符流:Reader/Writer
1. 字符流 vs 字节流
特性 | 字节流 | 字符流 |
---|
处理单位 | 字节(byte) | 字符(char) |
编码处理 | 需手动处理 | 自动转换 |
典型类 | FIleInputStream/FileOutputStream | FileReader/FileWriter |
适用场景 | 图片/视频等二进制文件 | 文本文件 |
2. 字符流读取操作
try (Reader reader = new FileReader("text.txt")) {
char[] buffer = new char[1024];
int charsRead;
while ((charsRead = reader.read(buffer)) != -1) {
String content = new String(buffer, 0, charsRead);
System.out.print(content);
}
}
3. 字符流写入操作
try (Writer writer = new FileWriter("log.txt", true)) {
writer.write("===== 操作日志 =====\n");
writer.write(LocalDateTime.now() + ": 用户登录\n");
writer.write("===================\n");
}
四、缓冲区:性能优化关键
1. 缓冲原理图解
+----------------+ +---------------+ +----------+
| 硬盘/网络 | --> | 缓冲区 | --> | 程序内存 |
| (低速设备) | <-- | (内存高速区域) | <-- | (处理区) |
+----------------+ +---------------+ +----------+
2. 缓冲流使用示例
try (BufferedReader br = new BufferedReader(new FileReader("bigfile.txt"));
BufferedWriter bw = new BufferedWriter(new FileWriter("output.txt"))) {
String line;
while ((line = br.readLine()) != null) {
bw.write(line.toUpperCase());
bw.newLine();
}
}
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("image.jpg"));
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("copy.jpg"))) {
byte[] buffer = new byte[8192];
int bytesRead;
while ((bytesRead = bis.read(buffer)) != -1) {
bos.write(buffer, 0, bytesRead);
}
}
五、字符编码:中文处理核心
1. 常见编码问题场景
FileReader reader = new FileReader("中文.txt");
Reader properReader = new InputStreamReader(
new FileInputStream("中文.txt"), StandardCharsets.UTF_8);
2. 编码转换原理
+----------------+ +-------------------+ +-----------------+
| 字节数据 | --> | 解码(byte→char) | --> | 字符数据 |
| (硬盘存储) | <-- | 编码(char→byte) | <-- | (程序处理) |
+----------------+ +-------------------+ +-----------------+
六、Scanner:高级文本处理
1. 文本扫描示例
try (Scanner scanner = new Scanner(
new File("data.csv"), StandardCharsets.UTF_8)) {
scanner.useDelimiter(",|\n");
while (scanner.hasNext()) {
String id = scanner.next();
String name = scanner.next();
double price = scanner.nextDouble();
System.out.printf("产品ID: %s, 名称: %s, 价格: %.2f%n",
id, name, price);
}
}
2. Scanner核心方法
方法 | 功能 | 返回值 |
---|
next() | 读取下一个标记 | String |
nextInt() | 读取整数 | int |
nextLine() | 读取整行 | String |
useDelimiter() | 设置分隔符 | Scanner |
hasNext() | 检查时候有更多输入 | boolean |
七、异常处理最佳实践
1. 常见IO异常类型
异常类型 | 触发场景 | 处理建议 |
---|
FileNotFoundException | 文件不存在 | 检查路劲或创建文件 |
SecurityException | 权限不足 | 修改权限或选择其他位置 |
IOException | 通用IO错误 | 关闭资源并记录日志 |
UnsupportEncodingException | 无效编码 | 使用StandardCharsets枚举 |
2. 防御性编程示例
public void safeCopy(File source, File target) throws IOException {
if (!source.exists()) {
throw new FileNotFoundException("源文件不存在: " + source);
}
if (!source.canRead()) {
throw new SecurityException("无读取权限: " + source);
}
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
}
}
结语
Java文件操作以File类管理文件系统,字节流处理二进制数据,字符流解决文本编码问题。缓冲区提升IO效率,try-with-resources确保资源释放,显式指定编码避免乱码,权限检查保障操作安全。这套机制支撑着从配置文件到大数据处理的各类场景。文件操作没有银弹,但有永恒的原则:理解数据流向,尊重系统资源,敬畏每一字节的重量。 这不仅是技术之道,更是构建可靠系统的哲学基石。