java 读取resource目录下的文件

  1. springboot提供的 org.springframework.core.io.ClassPathResource
    @Test
    public void classPathResourceTest() throws IOException {
        ClassPathResource resource = new ClassPathResource("template/cert.docx");
        try(InputStream ins = resource.getInputStream()){
            log.info("classLoader resource inputStream: {}", ins);
        }
    }
  1. 使用getClass()下的方法,jar包情况下最好使用getResourceAsStream来获取避免在服务器上出现路径匹配不上导致失败的问题.
    @Test
    public void javaTest() throws IOException {
        // 直接resource下的资源[getResource(?)] 可以不用传入classpath: . 但是需要注意比如从/开始路径
        URL resource = getClass().getResource("/template/xxx.docx");
        if (resource != null) {
            log.info("classLoader resource: {}", resource);
        }

        // 直接resource下的资源[getResourceAsStream(?)] 可以不用传入classpath: . 但是需要注意比如从/开始路径
        try (InputStream ins = getClass().getResourceAsStream("/template/xxx.docx")) {
            if (ins != null) {
                log.info("classLoader resource inputStream: {}", ins);
            }
        }

        // 获取类加载器资源[getClassLoader()] 可以不用传入classpath:
        try (InputStream ins = getClass().getClassLoader().getResourceAsStream("template/xxx.docx")) {
            if (ins != null) {
                log.info("classLoader resource inputStream: {}", ins);
            }
        }
    }
  1. springBoot提供的工具类 org.springframework.util.ResourceUtils
    @Test
    public void ResourceUtilsTest() throws IOException {
        // 不需要传入classpath:
        File file = ResourceUtils.getFile("template/xxx.docx");
        log.info("file:{}", file.getAbsolutePath());
    }

ps: 本地测试可以使用File或文件路径,但是达成jar的情况最好使用InputStream,避免其他意外.

posted @ 2025-04-21 10:34  wds09  阅读(233)  评论(0)    收藏  举报