起因:经常性的需要获取包内文件,一般是拿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

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

被折叠的 条评论
为什么被折叠?



