Java File exists()方法及示例

来源:这里教程网 时间:2026-02-17 20:53:34 作者:

Java File exists()方法及示例

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

语法

public boolean exists()
file.exists()

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

返回值: 如果由抽象文件名表示的文件存在或不存在,该函数返回 布尔值

异常: 如果对文件的写入权限被拒绝,该方法会抛出 安全异常

实现: 考虑在一个系统的本地目录下的文件,本地目录如下所示。

“F:\\program.txt”

例1 :

// Java Program to Illustrate exists() method of File Class // Importing input output classesimport java.io.*; // Main classpublic 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");    }}

输出

Exists

现在让我们考虑文件可写的情况(”F:\\program1.txt”)。

例2 :

// Java program to demonstrate// exists() method of File Class // Importing input output classesimport java.io.*; // Main classpublic 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

相关推荐