springboot打成jar后获取classpath下的文件

直接上代码  

JAR包用这个

		//获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		// 获取远程服务器IP和端口
		try {
			//获取所有匹配的文件
            Resource[] resources = resolver.getResources("static/images/faceSearch/*.*");
            for(Resource resource : resources) {
                //获得文件流,因为在jar文件中,不能直接通过文件资源路径拿到文件,但是可以在jar包中拿到文件流
                InputStream stream = resource.getInputStream();
                if (log.isInfoEnabled()) {
                	log.info("读取的文件流  [" + stream + "]");
                }
                String targetFilePath =env.getProperty("faceSearchDemo.faceSerachPics")+resource.getFilename();
                if (log.isInfoEnabled()) {
                	log.info("放置位置  [" + targetFilePath + "]");
                }
                File ttfFile = new File(targetFilePath);
                if(!ttfFile.getParentFile().exists()) {
                	ttfFile.getParentFile().mkdir();
                }
                FileUtils.copyInputStreamToFile(stream, ttfFile);
            }
		}catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}	

因为Springboot会将项目 打成 jar包,所以用下面的代码来获取文件,在本地eclipse上是可以运行获得到的,但在服务器上是不行的,必须要使用上面的代码。

 

 /**
     * 下载模板文件
     *
     * @throws IOException
     */
    @GetMapping(value = "/templateLableDownLoad")
    //@ResponseBody
    public void templateLableDownLoad(HttpServletResponse response) throws IOException {
        //获取容器资源解析器
        ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
//        Resource[] resources = resolver.getResources("/excelTemplate/label.xls");
        InputStream inputStream = this.getClass().getResourceAsStream("/excelTemplate/label.xls");
//        File file = resources[0].getFile();
        FileUtil.downloadExcelFile(response, inputStream);
    }

 

特别要注意的是:不是项目static / templates 目录下创建的文件 使用一下代码来获取流文件

 

InputStream inputStream=this.getClass().getResourceAsStream("/excelTemplate/label.xls");

WAR可以用这个

File file = ResourceUtils.getFile("classpath:static/images/faceSearch");
 if (file.exists()) {
	File[] files = file.listFiles();
	List<String> imageList = new ArrayList<>();
	if (files != null) {
		for(File fileC :files) {
			imageList.add(fileC.getName());
		}
	}
model.addAttribute("faceSerachImgList", imageList);

其他获取resources 目录下的文件的方法

File files = new ClassPathResource("templates/aa/a.html").getFile();

 

  • 5
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

古月_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值