JAVA Spring Boot 获取 Jar包内文件 File

本文探讨了在Spring Boot中由于Java的限制,直接通过getFile获取Jar包内的File会失败的原因,并提供了解决方案,即通过Resource转换并复制到临时文件来获取File类型。

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

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

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


	/**
	 * Resolve the given resource URL to a {@code java.io.File},
	 * i.e. to a file in the file system.
	 * @param resourceUrl the resource URL to resolve
	 * @param description a description of the original resource that
	 * the URL was created for (for example, a class path location)
	 * @return a corresponding File object
	 * @throws FileNotFoundException if the URL cannot be resolved to
	 * a file in the file system
	 */
	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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值