Java如何检查文件是否存在?

要检查文件或目录是否存在,我们可以利用java.io.File.exists()方法。此方法返回true或false。在检查其是否存在之前,我们需要创建一个实例,File该实例代表文件或目录的抽象路径名。有了File实例后,我们可以调用exists()方法进行验证。

package org.nhooo.example.io;

import java.io.File;
import java.io.FileNotFoundException;

public class FileExists {
    public static void main(String[] args) throws Exception {
        // 创建要定义的配置文件的抽象定义
        // 读。
        File file = new File("applicationContext-hibernate.xml");

        // 打印文件在文件系统中的确切位置。
        System.out.println("File = " + file.getAbsolutePath());

        // 如果是配置文件,则applicationContext-hibernate.xml
        // 当前路径中不存在的抛出异常。
        if (!file.exists()) {
            String message = "Cannot find configuration file!";
            System.out.println(message);
            throw new FileNotFoundException(message);
        }

        // 在这里继续应用逻辑!
    }
}