JAVA Spring Boot 获取 Jar包内文件 File

JAVA Spring Boot 获取 Jar包内文件 File,第1张

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
        

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5660854.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-16
下一篇 2022-12-16

发表评论

登录后才能评论

评论列表(0条)

保存