← 中文资源

简体中文版本

Files exists 与 notExists 三态

exists() 与 notExists() 是三态接口:状态无法判定(如权限不足)时都返回 false,成对比较才能区分“确实缺失”与“无法判断”。

阅读英文原文

实现说明

除了类 FilesExistsNotExists,文件里再无其他定义。

使用要点

  • 跑完文件,输出里会留下标记——exists(present) =、notExists(present) =、exists(missing) =。

常见问题

运行「Files exists 与 notExists 三态」会打印什么?

运行文件本身,exists(present) =、notExists(present) =、exists(missing) = 这些前缀各对应一段演示逻辑。

核心语句

Path missing = present.resolveSibling("missing.cfg");
Path present = Files.createTempFile("cfg-", ".tmp");
Files.delete(present);

代码示例

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class FilesExistsNotExists {

    public static void main(String[] args) throws IOException {
        Path present = Files.createTempFile("cfg-", ".tmp");
        Path missing = present.resolveSibling("missing.cfg");

        // exists / notExists 都是三态:true / false / 未知(也返回 false)
        System.out.println("exists(present)    = " + Files.exists(present));
        System.out.println("notExists(present) = " + Files.notExists(present));
        System.out.println("exists(missing)    = " + Files.exists(missing));
        System.out.println("notExists(missing) = " + Files.notExists(missing));

        // 两个结果相同 = 状态无法判定(如权限不足),不能当作“不存在”处理
        System.out.println("state known for present = "
                + (Files.exists(present) != Files.notExists(present)));
        System.out.println("definitely missing = "
                + (!Files.exists(missing) && Files.notExists(missing)));

        Files.delete(present);
    }
}