🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Java 中如何检查文件是否存在 > 原文: [https://howtodoinjava.com/java/io/how-to-check-if-file-exists-in-java/](https://howtodoinjava.com/java/io/how-to-check-if-file-exists-in-java/) 在本教程中,我们将学习如何测试**以检查文件是否存在**或 Java 中给定路径中是​​否存在目录。 ## 1\. 使用`File.exists()`方法检查文件是否存在 要测试是否存在文件或目录,请使用 Java `java.io.File`类的`exists()`方法,如下所示: ```java File tempFile = new File("c:/temp/temp.txt"); boolean exists = tempFile.exists(); ``` 如果上述方法返回`true`,则文件或目录确实存在,否则不存在。 ```java 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(); } } } ``` 程序输出。 ```java Temp file exists : true ``` ## 2\. `Files.exists()`和`Files.notExists()`方法 [Java NIO](https://howtodoinjava.com/java-nio-tutorials/) 还提供了测试文件是否存在的好方法。 为此使用`Files.exists()`方法或`Files.notExists()`方法。 ```java final Path path = Files.createTempFile("testFile", ".txt"); Files.exists(path); //true //OR Files.notExists(path); //false ``` ## 3\. 检查文件是否可读,可写或可执行 要验证程序是否可以根据需要访问文件,可以使用`isReadable(Path)`,`isWritable(Path)`和`isExecutable(Path)`方法 。 用于测试文件是否可读,可写和可执行的 Java 程序。 ```java final Path path = ...; Files.isReadable(path); //OR Files.isWritable(path); //OR Files.isExecutable(path); ``` 这就是与**检查 Java 中是否存在文件或目录**相关的快速提示。 通过检查程序的可写属性来测试是否允许程序向其添加内容。 学习愉快! 参考: [Java 文档](https://docs.oracle.com/javase/tutorial/essential/io/check.html)