原文: https://howtodoinjava.com/java/io/how-to-check-if-file-exists-in-java/

在本教程中,我们将学习如何测试以检查文件是否存在或 Java 中给定路径中是否存在目录。

1. 使用File.exists()方法检查文件是否存在

要测试是否存在文件或目录,请使用 Java java.io.File类的exists()方法,如下所示:

  1. File tempFile = new File("c:/temp/temp.txt");
  2. boolean exists = tempFile.exists();

如果上述方法返回true,则文件或目录确实存在,否则不存在。

import java.io.File;
import java.io.IOException;

public class TemporaryFileExample
{
   public static void main(String[] args)
   {
      File temp;
      try
      {
         temp = File.createTempFile("myTempFile", ".txt");

         boolean exists = temp.exists();

         System.out.println("Temp file exists : " + exists);
      } catch (IOException e)
      {
         e.printStackTrace();
      }
   }
}

程序输出。

Temp file exists : true

2. Files.exists()Files.notExists()方法

Java NIO 还提供了测试文件是否存在的好方法。 为此使用Files.exists()方法或Files.notExists()方法。

final Path path = Files.createTempFile("testFile", ".txt");

Files.exists(path);     //true

//OR

Files.notExists(path);  //false

3. 检查文件是否可读,可写或可执行

要验证程序是否可以根据需要访问文件,可以使用isReadable(Path)isWritable(Path)isExecutable(Path)方法 。

用于测试文件是否可读,可写和可执行的 Java 程序。

final Path path = ...;

Files.isReadable(path);

//OR

Files.isWritable(path);

//OR

Files.isExecutable(path);

这就是与检查 Java 中是否存在文件或目录相关的快速提示。 通过检查程序的可写属性来测试是否允许程序向其添加内容。

学习愉快!

参考:

Java 文档