exists() 函数是 Java 中 File 类的一部分。此函数确定 是抽象文件名表示的文件或目录是否存在。如果抽象文件路径存在,则函数返回 true,否则返回 false。
语法:
public boolean exists()
file.exists()
参数:此方法不接受任何参数。
返回值:如果抽象文件名表示的文件存在,该函数将返回布尔值。
例外:如果拒绝对文件的写入访问权限,此方法将引发 Security Exception
实现:考虑 file on local directory is on the system where local directory is as below provided.
// Java Program to Illustrate exists() method of File Class
//exists() 函数是 Java 中 File 类的一部分。此函数确定 是抽象文件名表示的文件或目录是否存在。如果抽象文件路径存在,则函数返回 true,否则返回 false。
//语法:
//public boolean exists()
//file.exists()
//参数:此方法不接受任何参数。
//返回值:如果抽象文件名表示的文件存在,该函数将返回布尔值。
//例外:如果拒绝对文件的写入访问权限,此方法将引发 Security Exception
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Getting the file by creating object of File class
File f = new File("F:\\program.txt");
// Checking if the specified file exists or not
if (f.exists())
// Show if the file exists
System.out.println("Exists");
else
// Show if the file does not exists
System.out.println("Does not Exists");
}
}
//
// Java program to demonstrate
// exists() method of File Class
// Importing input output classes
import java.io.*;
// Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
// Getting the file
File f = new File("F:\\program1.txt");
// Checking if the specified file
// exists or not
if (f.exists())
// Print message if it exists
System.out.println("Exists");
else
// Print message if it does not exists
System.out.println("Does not Exists");
}
}