一、获取Jar包内File文件失败的原因起因:经常性的需要获取包内文件,一般是拿resource,今天的需求是需要获取File类型。但在调用getFile的时候会报错。
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-io2.6
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)