您可以使用File类和Files类以两种方式验证系统中是否存在特定文件。
java.io包的名为File的类表示系统中的文件或目录(路径名)。此类提供了各种方法来对文件/目录执行各种操作。
此类提供各种方法来处理文件,如果存在()方法,则该类将验证当前File对象表示的文件或目录是否存在,如果存在,则返回true,否则返回false。
以下Java程序验证系统中是否存在指定的文件。它使用File类的方法。
import java.io.File;
public class FileExists {
public static void main(String args[]) {
//创建文件对象
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
自从Java 7引入Files类以来,它包含对文件,目录或其他类型的文件进行操作的(静态)方法。
该类提供一个名为的方法exists(),如果系统中存在当前对象所代表的文件,则该方法返回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 = 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