You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java Springboot中File.list()返回null:Windows正常Unix环境触发NPE

问题:Windows正常运行的文件目录代码在UNIX环境触发空指针异常

我编写了如下代码:

File folder = new File("./src/main/resources/uploads");
LOGGER.info("Read folder - {}", folder.getName()); // prints uploads correctly
folder.setReadable(true, false);
folder.setWritable(true, false);
String[] directories = folder.list();
System.out.println(directories.length)// throws an NPE here.

该代码在Windows机器上运行正常,但在UNIX环境中触发空指针异常(NPE)。我尝试添加或移除以下代码:

folder.setReadable(true, false);
folder.setWritable(true, false);

uploads是我手动创建的目录,且本地运行无问题,请问我哪里操作有误?


分析与解决

  • 核心原因:folder.list()返回null,说明UNIX环境下程序无法正常访问目标目录,主要排查路径和权限两个方向。
  • 路径验证:
    UNIX下程序的工作目录可能和Windows不同,你打印的folder.getName()只显示最后一级目录,无法确认完整路径是否正确。先打印绝对路径确认:
    System.out.println("Full folder path: " + folder.getAbsolutePath());
    
    核对输出路径是否和你手动创建的uploads目录一致,避免因工作目录差异导致路径错误。
  • 权限修复:
    1. folder.setReadable(true, false)的第二个参数false仅对目录所有者生效,如果运行程序的用户不是目录所有者,这个设置不会起作用。先确认程序运行用户对uploads目录的读权限。
    2. 手动创建的目录在UNIX下默认权限可能限制其他用户访问,通过终端执行ls -l ./src/main/resources/查看目录的权限和所有者,确保运行程序的用户拥有读权限。
  • 代码健壮性优化:
    在调用list()前增加前置检查,避免NPE:
    if (folder.exists() && folder.isDirectory() && folder.canRead()) {
        String[] directories = folder.list();
        if (directories != null) {
            System.out.println(directories.length);
        } else {
            LOGGER.error("Failed to read contents of directory: {}", folder.getAbsolutePath());
        }
    } else {
        LOGGER.error("Directory does not exist or is not readable: {}", folder.getAbsolutePath());
    }
    

内容的提问来源于stack exchange,提问作者PuneethC99

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:52:21