答案:Java中IO操作需捕获如FileNotFoundException、IOException等异常,使用try-catch或try-with-resources确保资源关闭与程序健壮性。
在Java中进行输入输出操作时,经常会遇到各种异常情况,比如文件不存在、权限不足、磁盘已满等。为了程序的健壮性,必须正确捕获并处理这些异常。Java的IO操作主要通过java.io包中的类实现,所有检查型异常都继承自IOException,因此可以通过try-catch块来捕获和处理。
了解常见的IO异常有助于针对性地处理问题:
最基本的处理方式是使用try-catch结构包裹IO操作代码:
import java.io.*;
public class FileReadExample {
public static void main(String[] args) {
FileReader file = null;
try {
file = new FileReader("data.txt");
int content;
while ((content = file.read()) != -1) {
System.out.print((char) content);
}
} catch (FileNotFoundException e) {
System.err.println("文件未找到:" + e.getMessage());
} catch (IOException e) {
System.err.println("读取文件时发生错误:" + e.getMessage());
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.err.println("关闭文件失败:" + e.getMessage());
}
}
}
}
}
从Java 7开始,推荐使用try-with-resources语句,它能自动关闭实现了AutoCloseable接口的资源,避免资源泄漏:
import java.io.*;
public class TryWithResourcesExample {
public static void readFile(Str
ing fileName) {
try (FileReader file = new FileReader(fileName);
BufferedReader reader = new BufferedReader(file)) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (FileNotFoundException e) {
System.err.println("文件不存在:" + fileName);
} catch (IOException e) {
System.err.println("IO异常:" + e.getMessage());
}
}
}
在这个例子中,FileReader和BufferedReader都会在try块结束时自动关闭,无需手动调用close()方法。