📜  Java中的 File exists() 方法及示例

📅  最后修改于: 2022-05-13 01:55:02.234000             🧑  作者: Mango

Java中的 File exists() 方法及示例

exists()函数是Java中 File 类的一部分。该函数确定抽象文件名所表示的文件或目录是否存在。如果抽象文件路径存在,则该函数返回 true,否则返回 false。

句法:

public boolean exists()
file.exists()

参数:此方法不接受任何参数。

返回值:如果抽象文件名表示的文件存在与否,函数返回布尔值

异常:如果拒绝对文件的写访问,此方法将引发安全异常

实施:考虑系统上本地目录上的文件,其中本地目录如下提供。

示例 1:

Java
// Java Program to Illustrate 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 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
// 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");
    }
}


输出:

Exists

示例 2:

Java

// 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");
    }
}

输出:

Does not Exists