java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java文件读写与异常处理

Java文件读写与异常处理从入门到实战指南

作者:小poop

本文详细讲解Java文件输入输出与异常处理,涵盖File、Scanner、PrintWriter等类的使用,并重点介绍如何处理IOException等异常,助你写出稳健的专业Java代码,感兴趣的朋友跟随小编一起看看吧

在Java编程中,文件输入输出异常处理是两个紧密相连的核心技能。无论是读取配置文件、写入日志,还是处理用户上传的数据,都离不开对文件的操作。而文件操作中又充满了各种不确定性(文件不存在、权限不足、IO错误等),这就离不开异常处理机制。

本文将结合Java标准库中的FileScannerPrintWriter等类,系统讲解如何安全、优雅地进行文本文件的读写,并结合异常处理机制,让程序更加健壮。

一、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 类,不仅可以读取控制台输入,也可以读取文件。

步骤

  1. 创建 File 对象
  2. File 对象传给 Scanner 构造器
  3. 使用 nextLine()nextInt() 等方法读取
  4. 关闭 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

四、异常处理:让程序更安全

文件操作中常见的异常包括:

使用 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 异常

类型父类是否必须处理常见例子
CheckedException(非RuntimeException)IOException, FileNotFoundException
UncheckedRuntimeException / ErrorNullPointerException, 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+),自动关闭资源,更加简洁安全。

总结

掌握文件读写与异常处理,是走向Java实战开发的重要一步。希望这篇文章能帮助你写出更稳健、更专业的Java代码。

到此这篇关于Java文件读写与异常处理从入门到实战指南的文章就介绍到这了,更多相关Java文件读写与异常处理内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文