【问题标题】:spring boot ResourceLoader traverse the files in the jar packagespring boot ResourceLoader 遍历jar包中的文件
【发布时间】:2018-03-06 10:20:58
【问题描述】:

我使用 spring 的 ResourceLoader 来遍历 jar 中的文件。但我想知道文件的类型(目录或文件)。

Resource resource = defaultResourceLoader.getResource(templatePathPrefix + File.separator + templateSourcePath);
    File templateSourceFile = null;
    try {
         //throws java.io.FileNotFoundException:
        templateSourceFile = resource.getFile();
    } catch (IOException e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot find file " + resource, e);
    }
 if (templateSourceFile.isDirectory()) {
    System.out.println("it is directory");
 } else {
    System.out.println("it is just file");
 }

我知道:

resource.getInputStream() 

可以获取文件的内容。但我想知道文件的类型。

【问题讨论】:

    标签: java spring spring-boot jar filenotfoundexception


    【解决方案1】:

    Spring 的ResourceLoader 用于为类路径、文件系统、Web 等上的资源创建资源处理程序。 它的目的不是遍历jar文件的内容并探测文件vs目录。

    我不确定您的最终目标是什么,但是对于来自 ResourceLoader 的单个加载资源,您可以执行以下操作:

    String filename = resource.getFilename();
    String type = URLConnection.guessContentTypeFromName(resource.getFilename());
    

    这将为您提供文件类型,从扩展名中猜测。

    遍历 Jar 条目

    为了遍历所有 jar 条目,您必须在运行时加载 jar 文件并执行以下操作:

        //String or File handler to JAR file
        JarFile jar = new JarFile(file);
        Enumeration<JarEntry> entries = jar.entries();
    
        while (entries.hasMoreElements()) {
            JarEntry jarEntry = entries.nextElement();
            System.out.println(jarEntry.getName() + ": " + jarEntry.isDirectory());
        }
    
        jar.close();
    

    另一种方法是将 jar 文件作为 Zip 打开并使用ZipEntry 探测文件与目录,或者为 Jar 的内容创建一个新的文件系统 (FileSystems.newFileSystem),然后您可以使用 @987654327直接@和File

    【讨论】:

      猜你喜欢
      • 2017-06-04
      • 2018-03-05
      • 1970-01-01
      • 2018-04-01
      • 2017-10-23
      • 2013-06-29
      • 2019-05-31
      • 1970-01-01
      • 2019-08-06
      相关资源
      最近更新 更多