SpringBoot读取classpath文件 SpringBoot 怎样读取classpath下的文件

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

SpringBoot读取classpath文件 SpringBoot 怎样读取classpath下的文件

东京易冷   2021-06-16 我要评论
想了解SpringBoot 怎样读取classpath下的文件的相关内容吗,东京易冷在本文为您仔细讲解SpringBoot读取classpath文件的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot,读取classpath下文件,classpath文件读取,下面大家一起来学习吧。

SpringBoot 读取classpath下文件

开发过程中,必不可少的需要读取文件,对于打包方式的不同,还会存在一些坑,比如以jar包方式部署时,文件都存在于jar包中,某些读取方式在开发工程中都可行,但是打包后,由于文件被保存在jar中,会导致读取失败。

这时就需要通过类加载器读取文件,类加载器可以读取jar包中的class类当然也可以读取jar包中的文件。

// 方法1:获取文件或流
this.getClass().getResource("/")+fileName;
this.getClass().getResourceAsStream(failName);
// 方法2:获取文件
File file = org.springframework.util.ResourceUtils.getFile("classpath:test.txt");
// 方法3:获取文件或流
ClassPathResource classPathResource = new ClassPathResource("test.txt");
classPathResource .getFile();
classPathResource .getInputStream();
// >>>>>>>>>>>>>>>> 下面方法可以读取jar包下文件
假设resources目录下有一个test.txt文件,首先获得当前的类加载器,通过类加载器读取文件。
// 方法1
InputStream io = Thread.currentThread().getContextClassLoader().getResourceAsStream("test.txt");
// 方法2
InputStream io = getClass().getClassLoader().getResourceAsStream("test.txt");

注意:

Spring工具类会对classpath路径做处理,类加载器不会对classpath做处理,因此使用类加载器读取文件,路径中不要添加classpath

SpringBoot项目打包成jar后获取classpath下文件失败

公司的一个SpringBoot项目中,有需要下载文件模板的需求,按理来说分布式项目文件都应该上传到文件服务器,但是由于文件不是太多于是就放在了classpath下,在本地开发的时候发现都能正常下载文件,但是打包成jar上传到Linxu测试环境上就报错,找不到classpath路径。

原因

原因是项目打包后Spring试图访问文件系统路径,但无法访问JAR包中的路径。我们使用ResourceUtils.getFile("classpath:");这样的方式是获取不到路径的。

解决方案

我们虽然不能直接获取文件资源路径,但是我们可以通过流的方式读取资源,拿到输入流过后我们就可以对其做操作了。关键代码如下:

ClassPathResource resource = new ClassPathResource("\\static\\pattern\\test.txt");    // static/pattern下的 test.txt文件
InputStream in = resource.getInputStream();  //获取文件输入流

示例Demo

1. 在static下新建pattern目录,并新建一个名为 test.txt的文件

在这里插入图片描述

2. 新建DownloadController.java

代码如下:

package com.example.jekins.controller;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
@RestController
public class DownloadController {
    @GetMapping("/download/pattern")
    public void downloadPattern(HttpServletRequest request, HttpServletResponse response){
        System.out.println("开始下载文件.....");
        ClassPathResource resource = new ClassPathResource("\\static\\pattern\\test.txt");
        try {
        	//获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("test文件.txt",request,response,in);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    /**
     * 下载文件
     * @param fileName 下载文件名称
     * @param response 响应
     * @throws IOException 异常
     */
    public static void downFile(String fileName,HttpServletRequest request,
                                HttpServletResponse response,InputStream in) throws IOException {
        //输出流自动关闭,java1.7新特性
        try(OutputStream os = response.getOutputStream()) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/octet-stream; charset=UTF-8");
            byte[] b = new byte[in.available()];
            in.read(b);
            os.write(b);
            os.flush();
        } catch (Exception e) {
            System.out.println("fileName=" + fileName);
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }
}

3. 测试 使用Maven工具把项目打成jar包

在这里插入图片描述

在target下生成了jar包

在这里插入图片描述

进入jar包所在的文件夹,按住shift并右击,点击在此处打开命令行窗口。输入命令启动项目 java -jar 打包后的文件

在这里插入图片描述

我设置的端口是8086,浏览器地址栏输入http://127.0.0.1:8086/download/pattern

此时我们可以卡看到test.txt文件下载成功

在这里插入图片描述

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们