是春天资源文件或目录?
我使用spring Resource API并使用ResourcePatternResolver扫描我的类路径以查找文件。是春天资源文件或目录?
在一种情况下,扫描正在拾取预构建的jar和文件系统中的某些目录和文件。
无论哪种情况,“资源”都是文件或目录。如何可靠地检测资源是否指向目录或文件,无论是否在jar文件中?在一个jar文件中调用getFile()
会抛出异常,所以我不能像我最初尝试的那样使用那个加isFile()
。
我觉得你可以只通过一个try catch块围绕代码检查文件:
boolean isFile = true;
try {
resource.getFile()
...
} catch (...Exception e) {
ifFile = false
}
Spring的Resource
接口,就是要为抽象访问底层资源一个更强大的接口。
它有时包装文件,有时不包括。
它有6个内置的工具:UrlResource
,ClassPathResource
,FileSystemResource
,ServletContextResource
,InputStreamResource
,ByteArrayResource
。
你可以实现自己的资源形式。
UrlResource
包装java.net.URL
,可用于访问通常通过URL访问的任何对象。如果您使用前缀http:
,则资源是一个URL。
ClassPathResource
表示应从类路径中获取的资源。如果类路径资源驻留在文件系统中,则此Resource
实现支持的分辨率为java.io.File
,但对于驻留在jar中并且尚未扩展(通过servlet引擎或任何环境)扩展到文件系统的classpath资源,该实现支持的分辨率为java.io.File
。为了解决这个问题各种Resource
实现总是支持分辨率为java.net.URL
。
FileSystemResource
是落实java.io.File
handles.It明显支持分辨率为File
和作为URL
。
InputStreamResource
是给定的InputStream
的资源实现。如果您需要将资源描述符保存在某处,或者您需要多次读取流,请不要使用它。
ByteArrayResource
是为给定的字节数组实现的Resource
。它为给定的字节数组创建一个ByteArrayInputStream。
所以,你不应该总是使用getFile()
如春的Resource
并不总是代表一个文件系统resource.For这个原因,我们建议您使用getInputStream()
访问资源的内容,因为它很可能为所有可能的资源类型的功能。
参考:Resources
我也有类似的要求,从我的搜索模式,不包括目录,解决了这个问题。然后,对于找到的每个资源,我都会查找路径中的父项,并确保在写入文件之前已创建目录。
在我的情况下,文件可能是在文件系统中,或者在classpath中,所以我检查URI第一的方案..
虽然我的搜索模式可能还是皮卡迪尔斯如果他们有名称的点,所以这将是更好的抓在这种情况下的例外 -
搜索模式 - classpath*:/**/sprout/plugins/**/*.*
示例代码 -
private void extractClientPlugins() throws IOException {
Resource[] resourcePaths = resolver.getResourcePaths(sproutPluginSearchPattern);
Path pluginFolderPath = Paths.get(sproutHome, "./plugins/");
pluginFolderPath.toFile().mkdirs();
if (resourcePaths.length == 0) {
log.info("No Sprout client side plugins found");
}
for (Resource resource : resourcePaths) {
try {
Path destinationPath = generateDestinationPath(pluginFolderPath, resource);
File parentFolder = destinationPath.getParent().toFile();
if (!parentFolder.exists()) {
parentFolder.mkdirs();
}
destinationPath.toFile().mkdirs();
copy(resource, destinationPath.toFile());
} catch (IOException e) {
log.error("could not access resource", e);
throw e;
}
}
}
private Path generateDestinationPath(Path rootDir, Resource resource) throws IOException {
String relativePath = null;
String scheme = resource.getURI().getScheme();
if ("JAR".contains(scheme.toUpperCase())) {
String[] uriParts = resource.getURL().toString().split("!");
relativePath = trimPluginPathPrefix(uriParts[1]);
} else {
String filePath = resource.getFile().getAbsolutePath();
relativePath = trimPluginPathPrefix(filePath);
}
return Paths.get(rootDir.toString(), relativePath);
}
private String trimPluginPathPrefix(String filePath) {
String[] pathParts = filePath.split("sprout/plugins/");
if (pathParts.length != 2) {
throw new RuntimeException("The plugins must be located in a path containing '**/sprout/plugins/*'");
}
return pathParts[1];
}
没有,这可能是一个目录或jar文件内的文件,这两种情况都会引发异常。上面的代码假定它是所有情况下的目录。 – 2012-04-19 08:28:24