繁体   English   中英

spring Resource 是文件还是目录?

[英]Is spring Resource a file or directory?

我正在使用 spring 资源 API 并使用 ResourcePatternResolver 扫描我的类路径中的文件。

在一种情况下,扫描会拾取预先构建的 jar 中的一些目录和文件,以及文件系统上的一些目录和文件。

在任何一种情况下,“资源”都是文件或目录。 如何可靠地检测资源是否指向目录或文件,无论是否在 jar 文件中? 在 jar 内的资源上调用getFile()会引发异常,因此我不能像最初尝试的那样使用它加上isFile()

Spring 的Resource接口旨在成为一个更强大的接口,用于抽象对低级资源的访问。

它有时会包装 File 有时不会。

它有六个内置实现: UrlResourceClassPathResourceFileSystemResourceServletContextResourceInputStreamResourceByteArrayResource

您可以实现自己的资源表单。

UrlResource包装了java.net.URL ,并可用于访问通常可通过 ZE6B391A8D2C4D45902A23A8B6585703 访问的任何 Object。 如果使用http:前缀,则资源为 URL。

ClassPathResource表示应该从类路径中获取的资源。 This Resource implementation supports resolution as java.io.File if the class path resource resides in the file system, but not for classpath resources which reside in a jar and have not been expanded (by the servlet engine, or whatever the environment is) to文件系统。 为了解决这个问题,各种Resource实现始终支持解析为java.net.URL

FileSystemResourcejava.io.File句柄的实现。它显然支持FileURL的解析。

InputStreamResource是给定InputStream的资源实现。 如果您需要将资源描述符保存在某处,或者如果您需要多次读取 stream,请不要使用它。

ByteArrayResource是给定字节数组的Resource实现。 它为给定的字节数组创建一个 ByteArrayInputStream。

所以你不应该总是使用getFile() ,因为 Spring 的Resource并不总是代表文件系统资源。因此,我们建议你使用getInputStream()来访问资源内容,因为它很可能是 function 对于所有可能的资源类型。

参考: 资源

我认为您可以通过 try catch 块包围检查文件的代码:

boolean isFile = true;

try {
   resource.getFile()
   ...
} catch (...Exception e) {
   ifFile = false
}

我有类似的要求,并通过从我的搜索模式中排除目录来解决它。 然后对于找到的每个资源,我在路径中查找父项,并确保在写入文件之前已创建目录。
在我的情况下,文件可能在文件系统中,或者在类路径中,所以我首先检查 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];
}  

在这个项目中使用它 -
https://github.com/savantly-net/sprout-platform/blob/master/sprout-core/src/main/java/net/savantly/sprout/core/ui/UiLoader.java

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM