在 Java 中,如何检查系统中是否存在文件?

java 8object oriented programmingprogramming更新于 2025/4/15 8:37:17

您可以使用 File 类和 Files 类以两种方式验证系统中是否存在特定文件。

使用 File 类

java.io 包中名为 File 的类表示系统中的文件或目录(路径名)。此类提供各种方法来对文件/目录执行各种操作。

此类提供各种方法来操作文件,它的 exist a () 方法验证当前 File 对象所表示的文件或目录是否存在,如果存在,则返回 true,否则返回 false。

示例

以下 Java 程序验证系统中是否存在指定文件。它使用 File 类的方法。

import java.io.File;
public class FileExists {
   public static void main(String args[]) {
      //创建 File 对象
      File file = new File("D:\source\sample.txt");
      //验证文件是否存在
      boolean bool = file.exists();
      if(bool) {
         System.out.println("File exists");
      } else {
         System.out.println("File does not exist");
      }
   }
}

输出

File exists

Files 类

自 Java 7 开始,Files 类被引入,它包含对文件、目录或其他类型文件进行操作的(静态)方法。

该类提供一个名为 exist() 的方法,如果当前对象所表示的文件存在于系统中,则该方法返回 true,否则返回 false。

示例

以下 Java 程序验证系统中是否存在指定文件。它使用 Files 类的方法。

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class FileExists {
   public static void main(String args[]) {
      //创建 Path 对象
      Path path = Paths.get("D:\sample.txt");
      //验证文件是否存在
      boolean bool = Files.exists(path);
      if(bool) {
         System.out.println("File exists");
      } else {
         System.out.println("File does not exist");
      }
   }
}

输出

File does not exist

相关文章