美文网首页
SpringBoot 读取Resources目录文件和JAR包里

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

作者: tickstep | 来源:发表于2020-11-07 14:22 被阅读0次

    简介

    我们经常会需要从以下位置读取文件内容
    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");
        }
    }
    

    相关文章

      网友评论

          本文标题:SpringBoot 读取Resources目录文件和JAR包里

          本文链接:https://www.haomeiwen.com/subject/mdnfbktx.html