Spring Boot 中读取本地及 Class Path 中的资源

2026-08-12 19:00:59  阅读 14 次 评论 0 条

我们可以通过前缀来切换读取目标,既能读取项目 resources 目录下的文件,也能读取服务器本地的相对或绝对路径文件

直接上代码:

package com.example.demo.controllers;

import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.StreamUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@RestController
@RequestMapping("/test")
public class TestController {

    // 传入当前类的 ClassLoader,避免多环境下的类加载器混乱问题
    private final ResourceLoader resourceLoader = new DefaultResourceLoader(TestController.class.getClassLoader());

    @GetMapping("index")
    public String test(){
        return getFile();
    }

    private String getFile(){
        String resourceName = "test-folder/test.txt";//如果没写前缀,默认按 classpath 处理
        String resourceFullName = "classpath:test-folder/test.txt";//指定了 classpath 前缀
        String relativePath ="file:./test-folder/test.txt";//相对路径相对的是Jvm的工作目录(调试的时候是工程根目录,运行的时候是执行命令时候的目录)
        String fileName = "file:D:\\test.txt";//绝对路径

        //这里可根据业务需要传入上述任意一种路径变量
        Resource resource = resourceLoader.getResource(resourceName);

        try (InputStream inputStream = resource.getInputStream()){
            String res = new String(StreamUtils.copyToByteArray(inputStream), StandardCharsets.UTF_8);
            System.out.println(res);
            return res;
        } catch (Exception e){
            System.out.println("文件读取失败:" + e.getMessage());
            return null;
        }
    }
}


路径规则总结:

  • classpath 读取: 对应代码中的 resourceNameresourceFullName。适合读取打包进 jar 包内部的静态资源。

  • 文件系统读取: 对应 relativePathfileName只要想读外部系统文件,就必须加上 file: 前缀。如果不加,系统会默认去 classpath 里面找。



微信扫码查看本文
本文地址:https://www.yangguangdream.com/?id=2276
版权声明:本文为原创文章,版权归 编辑君 所有,欢迎分享本文,转载请保留出处!
NEXT:已经是最新一篇了

发表评论


表情

还没有留言,还不快点抢沙发?