要说Ja va里哪两个技能最常打包出现,文件读写和异常处理肯定算一对儿。日常开发里,读个配置文件、写个日志、处理用户上传的数据,哪样都离不开文件操作。但文件操作这事,变数实在太多——文件可能不存在、权限不够、IO设备突然罢工……这时候,没有异常处理机制兜底,程序分分钟崩给你看。

这篇文章会结合Ja va标准库里的File、Scanner、PrintWriter这些常用类,系统讲讲怎么安全又优雅地读写文本文件,同时把异常处理机制揉进去,让代码真正健壮起来。
一、File类:文件与目录的抽象
File类是ja va.io包里代表文件或目录路径的对象。注意,它不操作文件内容,只负责以下这些事:
- 获取文件属性(大小、路径、是否可读写)
- 创建、删除、重命名文件或目录
- 判断文件是否存在、是否为目录等
示例:创建File对象
// Windows风格(注意转义)
File file1 = new File("D:\temp\test.txt");
// Unix风格(推荐)
File file2 = new File("D:/temp/test.txt");
// 分目录和文件名
File dir = new File("D:/myDir");
File file3 = new File(dir, "data.txt");
常用方法
| 方法 | 说明 |
|---|---|
getName() | 获取文件名 |
getAbsolutePath() | 获取绝对路径 |
exists() | 判断是否存在 |
isFile() / isDirectory() | 判断是文件还是目录 |
length() | 获取文件大小(字节) |
二、读文件:Scanner + File
Scanner这个类,大家平时可能更习惯用它读控制台输入。但它的能力远不止于此——拿来读文件同样顺手。
步骤
- 创建一个
File对象 - 把
File对象传给Scanner的构造器 - 用
nextLine()、nextInt()等方法逐行或按类型读取 - 用完记得关闭
Scanner
示例:读取文本文件
import ja va.io.*;
import ja va.util.Scanner;
public class ReadFileDemo {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("names.txt");
Scanner scanner = new Scanner(file);
while (scanner.hasNext()) {
String line = scanner.nextLine();
System.out.println(line);
}
scanner.close();
}
}
⚠️
Scanner的构造器会抛出FileNotFoundException,要么用try-catch兜住,要么在方法签名上声明。
三、写文件:PrintWriter + FileWriter
写文件方面,PrintWriter 是首选之一。print() 和 println() 用起来就跟往控制台打印一样自然。
基本写法(覆盖模式)
PrintWriter out = new PrintWriter("output.txt");
out.println("Hello, Ja va!");
out.println("File writing test.");
out.close();
追加模式
如果不想覆盖原有内容,FileWriter 的追加构造器正好派上用场:
FileWriter fw = new FileWriter("output.txt", true);
PrintWriter out = new PrintWriter(fw);
out.println("这行会被追加到文件末尾");
out.close();
注意:
PrintWriter同样会抛出IOException,方法签名里记得加上throws IOException。
四、异常处理:让程序更安全
文件操作里,常见的异常就那么几种:
FileNotFoundException:文件不存在IOException:读写过程中间出错NumberFormatException:数据格式不对(比如想把"abc"转成数字)
使用 try-catch 捕获异常
try {
File file = new File("data.txt");
Scanner sc = new Scanner(file);
while (sc.hasNext()) {
System.out.println(sc.nextLine());
}
sc.close();
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
}
多异常处理
try {
// 可能抛出多种异常的代码
} catch (FileNotFoundException e) {
System.out.println("文件不存在");
} catch (IOException e) {
System.out.println("IO错误");
}
✅ 子类异常必须写在父类异常之前,否则编译器会报错。
finally 子句:无论如何都会执行
Scanner sc = null;
try {
sc = new Scanner(new File("test.txt"));
// 读取文件
} catch (FileNotFoundException e) {
System.out.println("文件未找到");
} finally {
if (sc != null) {
sc.close(); // 保证资源被释放
}
}
五、抛出异常:throws 与 throw
throws:声明方法可能抛出异常
public void readFile(String path) throws FileNotFoundException {
Scanner sc = new Scanner(new File(path));
// ...
}
throw:手动抛出异常
if (amount < 0) {
throw new IllegalArgumentException("金额不能为负数");
}
自定义异常类
class NegativeBalanceException extends Exception {
public NegativeBalanceException(String msg) {
super(msg);
}
}
六、Checked vs Unchecked 异常
| 类型 | 父类 | 是否必须处理 | 常见例子 |
|---|---|---|---|
| Checked | Exception(非RuntimeException) | 是 | IOException, FileNotFoundException |
| Unchecked | RuntimeException / Error | 否 | NullPointerException, ArithmeticException |
文件操作中遇到的异常,大多数是 Checked Exception,不能视而不见,必须处理或声明抛出。
七、实战:完整的文件复制程序
来一个完整的文件复制示例,把前面说的知识点串起来:
import ja va.io.*;
public class FileCopy {
public static void main(String[] args) {
String src = "source.txt";
String dest = "dest.txt";
try (BufferedReader reader = new BufferedReader(new FileReader(src));
PrintWriter writer = new PrintWriter(new FileWriter(dest))) {
String line;
while ((line = reader.readLine()) != null) {
writer.println(line);
}
System.out.println("复制成功");
} catch (FileNotFoundException e) {
System.out.println("源文件不存在");
} catch (IOException e) {
System.out.println("IO错误:" + e.getMessage());
}
}
}
✅ 这里用的是 try-with-resources(Ja va 7+ 引入),资源会在try块结束后自动关闭,比手动在finally里写sc.close()更简洁也更安全。
总结
File类负责文件路径和属性,不碰内容Scanner+File是读文本文件的好搭配PrintWriter+FileWriter写文本文件,支持追加或覆盖- 文件操作必须对
IOException等 checked 异常有交代 - 用
try-catch-finally或try-with-resources确保资源释放 - 区分 checked 和 unchecked 异常,设计合理的异常处理策略
掌握文件读写与异常处理,算是跨入Ja va实战开发的一道重要门槛。希望这篇文章能帮你在实际项目中写出更稳健、更专业的代码。
