使用Files.isRegularFile()或file.exists()可提前判断文件是否存在,避免抛出FileNotFoundException。

在Java中,FileNotFoundException 是在尝试读取一个不存在的文件时抛出的异常。但如果你希望在抛出异常前就判断文件是否存在,避免异常发生,应该使用 java.io.File 类或 java.nio.file.Files 类提供的方法来检查文件状态。
使用 java.io.File 判断文件是否存在
通过 File.exists() 方法可以判断文件或目录是否存在:
- File file = new File("path/to/your/file.txt");
- if (file.exists()) {
- System.out.println("文件存在");
- } else {
- System.out.println("文件不存在");
- }
注意:exists() 返回 false 时,说明文件路径无效或文件确实不存在。同时建议配合 isFile() 确保是一个文件而不是目录。
使用 java.nio.file.Files(推荐方式)
Java 7 引入的 NIO.2 提供了更现代的方式:
立即学习“Java免费学习笔记(深入)”;
- Path path = Paths.get("path/to/your/file.txt");
- if (Files.exists(path)) {
- System.out.println("路径存在");
- } else {
- System.out.println("路径不存在");
- }
还可以进一步判断是否为普通文件:
- if (Files.isRegularFile(path)) {
- System.out.println("这是一个普通文件");
- }
如何避免 FileNotFoundException
在打开文件前先做存在性检查,能有效防止异常:
- Path path = Paths.get("data.txt");
- if (Files.isRegularFile(path)) {
- try (BufferedReader reader = Files.newBufferedReader(path)) {
- String line;
- while ((line = reader.readLine()) != null) {
- System.out.println(line);
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- } else {
- System.out.println("文件不存在或不是有效文件");
- }
基本上就这些。用 Files.exists() 或 file.exists() 提前判断,就能避免不必要的 FileNotFoundException,让程序更健壮。










