栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JAVA Spring Boot 获取 Jar包内文件 File

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JAVA Spring Boot 获取 Jar包内文件 File

起因:经常性的需要获取包内文件,一般是拿resource,今天的需求是需要获取File类型。但在调用getFile的时候会报错。

 一、获取Jar包内File文件失败的原因

getFile中URL_PROTOCOL_FILE 标明只能获取file,不能获取其他类型,不然统一报错,获取jar包内文件时protocol就不是file的。

	
	public static File getFile(URL resourceUrl, String description) throws FileNotFoundException {
		Assert.notNull(resourceUrl, "Resource URL must not be null");
		if (!URL_PROTOCOL_FILE.equals(resourceUrl.getProtocol())) {
			throw new FileNotFoundException(
					description + " cannot be resolved to absolute file path " +
					"because it does not reside in the file system: " + resourceUrl);
		}
		try {
			return new File(toURI(resourceUrl).getSchemeSpecificPart());
		}
		catch (URISyntaxException ex) {
			// Fallback for URLs that are not valid URIs (should hardly ever happen).
			return new File(resourceUrl.getFile());
		}
	}
 二、解决方法

方法很简单,先获取到jar 包内文件的resource,再通过复制流到临时文件的形式拿到,File类型的文件

ResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver();
        org.springframework.core.io.Resource[] files = resourcePatternResolver.getResources("classpath*:xxx.yml");
        if (files.length==0){
            throw new FileNotFoundException("xxx.yml cannot be resolved to absolute file path because it does not exist");
        }
        File file = File.createTempFile("xxx","yml");
        FileUtils.copyInputStreamToFile(files[0].getInputStream(), file);

FileUtils类,相关依赖如下:

 
            commons-io
            commons-io
            2.6
        

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/658781.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号