SpringBoot 读取Resources目录文件和JAR包里

2020-11-07  本文已影响0人  tickstep

简介

我们经常会需要从以下位置读取文件内容
1,系统本地文件夹下文件
2,工程src/main/resources 目录下文件
3,JAR包里面的src/main/resources 目录下文件
如果需要按照以上顺序去查找并读取文件内容,需要怎么做呢?

代码片段

示例代码如下

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;

import java.io.IOException;
import java.io.InputStream;

@Slf4j
public class FileTest {
    public Resource getResourceFile(String path) {
        InputStream in = getResourceFileStream(path);
        if (in == null) {
            return null;
        }
        byte[] buf = IoUtil.readBytes(in);
        return new ByteArrayResource(buf);
    }

    public InputStream getResourceFileStream(String path) {
        // try the read file from the local file system
        Resource resource = new FileSystemResource(FileUtil.getAbsolutePath(path));
        if (resource.exists()) {
            try {
                log.debug("Resource File Path = " + resource.getURI().getPath());
                return resource.getInputStream();
            } catch (IOException e) {
                log.debug("read file from file system error: " + path);
            }
        }

        // try to find file in internal .jar package
        InputStream in = this.getClass().getClassLoader().getResourceAsStream(path);
        if (in != null) {
            log.debug("Resource File Use JAR Package Internal File: " + path);
            return in;
        }
        return null;
    }

    public static void main(String[] args) {
        FileTest tool = new FileTest();

        // 读取本地文件夹文件
        tool.getResourceFileStream("/home/user/download/file.txt");

        // 读取工程 resources 目录下文件
        // 如果项目工程 resources 目录不存在该文件,则尝试去改代码所在的class的jar包中的 resources 目录去查找
        tool.getResourceFileStream("file.txt");
    }
}
上一篇下一篇

猜你喜欢

热点阅读