1. 输入/输出异常的层次结构
在 Java 中,处理文件和其他外部资源时几乎总会遇到所谓的输入/输出异常。它们是在读取或写入数据出现问题时被抛出的对象(throw)。例如,文件未找到、无访问权限,或者磁盘突然“累了”。
本讲的主角
在 Java 中,I/O 异常有一整套层次结构。以下是其中的主要成员:
- IOException — 所有 I/O 错误的基类。如果文件、流或网络出了问题——几乎总是它(或它的某个子类)“背锅”。
- FileNotFoundException — IOException 的子类:当你尝试打开一个不存在的文件,或路径不正确时出现。
其他派生类:
- EOFException — 同样是 IOException 的直接子类。表示在读取时意外到达文件末尾。
- MalformedInputException — 可以理解为“孙辈”:继承自 CharacterCodingException,而后者又继承自 IOException。当文件无法按指定编码正确解析时会出现这种错误(例如,期望 "UTF-8",却收到损坏的字节序列)。
- 另外还有 SocketException、ZipException 等专用“亲属”,各自负责不同的领域。层次越往下,适用场景越狭窄、越具体。
一张简化示意图:
java.lang.Exception
└── java.io.IOException
├── java.io.FileNotFoundException
├── java.io.EOFException
├── java.nio.charset.MalformedInputException
└── ... (others)
有趣的事实:
在 Java 中,几乎所有与文件相关的操作都需要声明或处理 IOException —— 这就是所谓的受检异常(checked exceptions)。编译器不会让你忘记处理错误!
2. 这些异常何时以及为何出现
打开不存在的文件
最常见的情况——你尝试打开一个文件,但它并不存在。这就像你到了车站,却发现这趟公交甚至不在时刻表上。
FileInputStream fis = new FileInputStream("abracadabra.txt"); // 砰!FileNotFoundException
在没有权限的情况下写入文件
如果你试图把文件写入一个没有权限的目录,可能会得到 FileNotFoundException 或 IOException(取决于具体情况)。
FileOutputStream fos = new FileOutputStream("/system/secret.txt"); // 砰!FileNotFoundException 或 IOException
由于介质损坏导致的读/写错误
有时文件是存在的,但磁盘损坏、文件被其他程序占用,或突然断电——这时会抛出带有不同消息的 IOException。
其他原因
- 文件是只读的,而你在尝试写入。
- 文件路径太长或包含无效字符。
- 文件正被其他进程使用。
- 磁盘已满。
- 在检查与使用之间,文件被其他进程删除了。
3. 使用 try-catch 进行处理
每当你处理文件、流或网络时——请使用 try-catch。这就像安全气囊:一旦出错,程序不会崩溃,而是能做出恰当响应。
如何正确捕获异常?
在 Java 中,应先捕获更具体的异常,再捕获更通用的异常。如果把通用的 catch(IOException e)放在前面,更具体的例如 FileNotFoundException 将不会被触发——控制流到不了它。
正确的结构:
try {
// 文件操作
} catch (FileNotFoundException e) {
// 处理“文件未找到”的情况
} catch (IOException e) {
// 处理其他 I/O 错误
}
为什么要这样?
因为 FileNotFoundException 是 IOException 的特例。如果你先捕获通用的情况,特例就无法到达它自己的 catch。
代码示例:打开文件时的错误处理
import java.io.*;
public class FileReaderExample {
public static void main(String[] args) {
String filename = "notes.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
System.out.println("文件的第一行:" + line);
reader.close();
} catch (FileNotFoundException e) {
System.out.println("未找到文件:" + filename);
} catch (IOException e) {
System.out.println("读取文件时发生错误:" + e.getMessage());
}
}
}
请注意:
即便你已经检查过文件是否存在,也要保留 try-catch —— 文件可能随时消失(例如被其他进程删除)。
4. 实践:编写带错误处理的代码
我们来写几个简单示例,让它们能正确应对文件缺失及其他错误。
步骤 1:尝试打开一个不存在的文件
import java.io.*;
public class NotesApp {
public static void main(String[] args) {
String filename = "my_notes.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line;
System.out.println("您的笔记:");
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (FileNotFoundException e) {
System.out.println("哎呀!未找到笔记文件:" + filename);
System.out.println("提示:请创建文件或检查名称。");
} catch (IOException e) {
System.out.println("读取文件时发生错误:" + e.getMessage());
}
}
}
步骤 2:为写文件添加处理
import java.io.*;
public class NotesWriter {
public static void main(String[] args) {
String filename = "my_notes.txt";
try {
BufferedWriter writer = new BufferedWriter(new FileWriter(filename, true)); // append: true
writer.write("新的笔记!\n");
writer.close();
System.out.println("笔记已成功添加!");
} catch (IOException e) {
System.out.println("写入文件时发生错误:" + e.getMessage());
}
}
}
步骤 3:带错误日志的通用示例
import java.io.*;
public class SafeFileCopier {
public static void main(String[] args) {
String source = "source.txt";
String target = "target.txt";
try {
BufferedReader reader = new BufferedReader(new FileReader(source));
BufferedWriter writer = new BufferedWriter(new FileWriter(target));
String line;
while ((line = reader.readLine()) != null) {
writer.write(line);
writer.newLine();
}
reader.close();
writer.close();
System.out.println("文件复制成功!");
} catch (FileNotFoundException e) {
System.out.println("未找到文件:" + e.getMessage());
} catch (IOException e) {
System.out.println("I/O 错误:" + e.getMessage());
}
}
}
建议:
在真实应用中,错误不只要打印到屏幕,还应记录到文件或日志中,以便之后排查问题。
5. 表格:常见的 I/O 异常
| 异常 | 何时出现? | 如何处理? |
|---|---|---|
|
文件未找到、路径不存在或无权限 | 提示用户,检查路径/权限,必要时创建文件 |
|
读取时意外到达文件末尾 | 提示文件损坏/不完整,尝试部分恢复数据 |
|
通用 I/O 错误(磁盘、权限、锁定) | 检查详情,正确结束操作,必要时重试 |
|
编码或文件结构不正确 | 提示文件损坏,尝试其他编码/来源 |
6. 处理 I/O 异常的常见错误
错误 1:只捕获通用的 Exception。 仅仅写 catch(Exception e)很诱人,但你将无法区分到底出了什么问题。最好先捕获具体异常(FileNotFoundException),然后再捕获通用的 IOException。
错误 2:出错时不关闭流。 如果你打开了文件,而后发生了异常,流可能会保持未关闭状态。请使用 try-with-resources,或在 finally 中关闭资源。
错误 3:忽略异常消息。 不要只输出“错误!”,而要显示详细信息:e.getMessage()。这有助于更快定位问题。
错误 4:写入时不处理 FileNotFoundException。 许多人认为 FileNotFoundException 只和读取有关。事实上它在写入时也可能出现(路径不正确、无创建文件的权限等)。
错误 5:不检查访问权限。 如果程序在受限权限下运行,很多文件操作都可能失败。务必考虑这一点并告知用户。
GO TO FULL VERSION