Java文件读写与异常处理从入门到实战指南
作者:小poop
在Java编程中,文件输入输出和异常处理是两个紧密相连的核心技能。无论是读取配置文件、写入日志,还是处理用户上传的数据,都离不开对文件的操作。而文件操作中又充满了各种不确定性(文件不存在、权限不足、IO错误等),这就离不开异常处理机制。
本文将结合Java标准库中的File、Scanner、PrintWriter等类,系统讲解如何安全、优雅地进行文本文件的读写,并结合异常处理机制,让程序更加健壮。
一、File类:文件与目录的抽象
File类是java.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
Java 提供了 Scanner 类,不仅可以读取控制台输入,也可以读取文件。
步骤
- 创建
File对象 - 将
File对象传给Scanner构造器 - 使用
nextLine()、nextInt()等方法读取 - 关闭
Scanner
示例:读取文本文件
import java.io.*;
import java.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,必须处理或声明。
三、写文件:PrintWriter + FileWriter
PrintWriter 类提供了 print() 和 println() 方法,非常适合写文本文件。
基本写法(覆盖模式)
PrintWriter out = new PrintWriter("output.txt");
out.println("Hello, Java!");
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:数据格式错误
使用 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 java.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(Java 7+),自动关闭资源,更加简洁安全。
总结
File类操作文件路径和属性Scanner+File读文本文件PrintWriter+FileWriter写文本文件- 文件操作必须处理
IOException等 checked 异常 - 使用
try-catch-finally或try-with-resources保证资源释放 - 区分 checked 和 unchecked 异常,合理设计异常处理策略
掌握文件读写与异常处理,是走向Java实战开发的重要一步。希望这篇文章能帮助你写出更稳健、更专业的Java代码。
到此这篇关于Java文件读写与异常处理从入门到实战指南的文章就介绍到这了,更多相关Java文件读写与异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!
