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

Spring子项目读取resources目录文件的异常问题求助

老哥,你这个问题我之前踩过一模一样的坑——直接把ClassLoader.getResource()返回的URL转成File对象肯定会抛出异常,尤其是当你的项目打包成JAR之后,根本找不到目标文件。我给你捋清楚原因和解决办法:

为什么会报错?

当你调用loader.getResource("/wm/device.txt").toString()时,得到的路径大概率是类似 jar:file:/path/to/your/project.jar!/wm/device.txt 这样的格式。这个URL指向的是JAR包内部的资源,而不是本地文件系统里的独立文件。new File(filepath) 只能识别本地文件系统的路径,自然会抛出FileNotFoundException。

两种正确的读取方式

1. 直接用输入流读取(推荐,通用所有场景)

不管你的资源是在本地开发的文件系统里,还是打包进JAR包,用getResourceAsStream()直接获取输入流都是最稳妥的方式,而且还能避免资源泄漏:

static final ClassLoader loader = DummyClass.class.getClassLoader();

public void getData(String ip) throws IOException {
    // 直接获取资源输入流,无需关心资源位置
    try (InputStream inputStream = loader.getResourceAsStream("/wm/device.txt");
         BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
        if (inputStream == null) {
            throw new FileNotFoundException("未找到资源文件:/wm/device.txt");
        }
        
        String line;
        while ((line = reader.readLine()) != null) {
            // 在这里处理读取到的每一行内容
            System.out.println(line);
        }
    }
}

这里用了try-with-resources语法,会自动帮你关闭输入流和Reader,不用手动写close(),非常省心。

2. 仅本地开发时获取File对象(不推荐用于生产)

如果你只是在本地开发阶段需要操作File对象(比如要修改文件内容),可以把URL转成URI再创建File,但这种方式打包成JAR后完全失效:

static final ClassLoader loader = DummyClass.class.getClassLoader();

public void getData(String ip) throws IOException, URISyntaxException {
    URL resourceUrl = loader.getResource("/wm/device.txt");
    if (resourceUrl == null) {
        throw new FileNotFoundException("未找到资源文件:/wm/device.txt");
    }
    
    // 仅本地文件系统有效,JAR内资源会报错
    File file = new File(resourceUrl.toURI());
    try (FileReader fileReader = new FileReader(file);
         BufferedReader reader = new BufferedReader(fileReader)) {
        String line;
        while ((line = reader.readLine()) != null) {
            // 处理内容
            System.out.println(line);
        }
    }
}

几个额外注意点

  • 资源路径要写对:/wm/device.txt开头的斜杠表示从classpath根目录查找,确保你的文件确实放在src/main/resources/wm/device.txt,打包后会自动进入classpath的wm目录下。
  • 一定要判空:调用getResource()或getResourceAsStream()后,先检查返回值是否为null,避免因为路径写错导致的NullPointerException。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:09:36