确定文件或目录是否存在于 Java 中

方法 java.io。用于检查文件或目录是否存在。如果抽象路径名指定的文件或目录存在,则此方法返回 true,如果不存在,则返回 false。File.exists()

演示这一点的程序如下 -

示例

import java.io.File;
public class Demo {
   public static void main(String[] args) {
      try {
         File file = new File("c:/JavaProgram/demo1.txt");
         file.createNewFile();
         System.out.println(file.exists());
      } catch(Exception e) {
         e.printStackTrace();
      }
   }
}

上述程序的输出如下 -

输出结果

true

现在让我们了解上面的程序。

方法 java.io。用于检查文件或目录是否存在,并打印该方法返回的布尔值。演示这一点的代码片段如下 -File.exists()

try {
   File file = new File("c:/JavaProgram/demo1.txt");
   file.createNewFile();
   System.out.println(file.exists());
} catch(Exception e) {
   e.printStackTrace();
}