温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

SpringBoot怎么读取classpath下的文件

发布时间:2021-06-16 13:46:20 来源:亿速云 阅读:825 作者:小新 栏目:开发技术

这篇文章主要介绍了SpringBoot怎么读取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的文件

SpringBoot怎么读取classpath下的文件

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包

SpringBoot怎么读取classpath下的文件

在target下生成了jar包

SpringBoot怎么读取classpath下的文件

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

SpringBoot怎么读取classpath下的文件

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

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

SpringBoot怎么读取classpath下的文件

感谢你能够认真阅读完这篇文章,希望小编分享的“SpringBoot怎么读取classpath下的文件”这篇文章对大家有帮助,同时也希望大家多多支持亿速云,关注亿速云行业资讯频道,更多相关知识等着你来学习!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI