如何在 Java 中检查文件是否在系统中的任何位置存在?
您可以使用 File 类和 Files 类两种方式来验证系统中是否存在特定文件。
使用 File 类
java.io 包中的名为 File 的类表示系统中的文件或目录(路径名)。此类提供了各种方法来对文件/目录执行各种操作。
此类提供各种方法来操作文件,其中的 exists() 方法验证当前 File 对象所表示的文件或目录是否存在,如果存在,则返回 true,否则返回 false。
示例
以下 Java 程序验证指定文件是否在系统中存在。它使用 File 类的方法。
import java.io.File;
public class FileExists {
public static void main(String args[]) {
//Creating a File object
File file = new File("D:\source\sample.txt");
//Verifying if the file exits
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 类,它包含(静态)方法,这些方法用于操作文件、目录或其他类型的文件。
该类提供了一个名为 exists() 的方法,如果当前对象(s)所表示的文件存在于系统中,则返回 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[]) {
//Creating a Path object
Path path = Paths.get("D:\sample.txt");
//Verifying if the file exits
boolean bool = Files.exists(path);
if(bool) {
System.out.println("File exists");
} else {
System.out.println("File does not exist");
}
}
}输出
File does not exist
广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP