java获取resources文件夹目录

发布时间:2024年01月18日

需求:获取reouurces目录下的文件:重点植物导入模版

?获取到文件:

 public static void main(String[] args) {
        // 获取 resource 目录下的所有文件
        ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        Resource[] resources = resourcePatternResolver.getResources("classpath*:/**/*.xml");
        for (Resource resource : resources) {
            System.out.println(resource.getURL());
        }
    }

?获取文件并下载:

/**
	 * 下载导出模板
	 */
	@GetMapping("/downloadFile")
	@ApiOperationSupport(order = 12)
	@ApiOperation(value = "下载", notes = "下载")
	public ResponseEntity<Resource> downloadFile() throws IOException {
		String encodedFileName = CommonUtil.encodeFileName(CommonConstant.BACKGROUND_RESOURCES_EXCEL);
		ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
		Resource[] resources = resourcePatternResolver.getResources("classpath*:/**/*.xlsx");
		Resource file = null;
		for (Resource resource : resources) {
			String url = resource.getURL().getPath();
			if (url.contains(CommonConstant.BACKGROUND_RESOURCES_EXCEL)) {
				file = resource;
			}
		}
		// 构建ResponseEntity对象
		HttpHeaders headers = new HttpHeaders();
		headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + encodedFileName + "\"");
		headers.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_OCTET_STREAM_VALUE);
		return ResponseEntity.ok()
			.headers(headers)
			.body(file);
	}

?

文章来源:https://blog.csdn.net/qq_34471241/article/details/135673283
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。