java.io.File class exists() method can be used to check if file exists or not in java. If file exists, it returns true else this method returns false.

java.io.Fileexist()方法可用于检查java中文件是否存在。 如果文件存在,则返回true,否则此方法返回false。

(Java Check if File Exists)

Let’s look at a simple program to check if a file exists or not in Java.

让我们看一个简单的程序,检查Java中文件是否存在。





package com.journaldev.files;

import java.io.File;
import java.io.IOException;

public class FileExists {

    public static void main(String[] args) {
        File file = new File("/Users/pankaj/source.txt");
        File notExist = new File("xyz.txt");
        
        try {
            System.out.println(file.getCanonicalPath() + " exists? "+file.exists());
            System.out.println(notExist.getCanonicalPath() + " exists? "+notExist.exists());
        } catch (IOException e) {
            e.printStackTrace();
        }
        
    }

}

Output of the above program is:

上面程序的输出是:





/Users/pankaj/source.txt exists? true
/Users/pankaj/JavaPrograms/xyz.txt exists? false

Note: When we provide a relative path to create a file object, Eclipse uses project root as the base directory. If you are running the program from the command line, then the current directory is used as the base directory.

注意 :当我们提供创建文件对象的相对路径时,Eclipse使用项目根目录作为基本目录。 如果从命令行运行程序,则将当前目录用作基本目录。