【问题标题】:Reading .cer files from jar file failing从 jar 文件中读取 .cer 文件失败
【发布时间】:2020-10-21 03:20:26
【问题描述】:

我试图在运行时安装客户端 SSL 证书。证书已经用 jar 打包,可在以下位置获得

尝试使用以下代码从上述路径读取所有可用的 .cer 文件时,失败了

 String rootPath = this.getClass().getClassLoader().getResource("certs/"+activeProfile+"/").getPath();
 File folder = new File(rootPath);
 File[] listOfFiles = folder.listFiles();

在调试时,我将“rootPath”作为“file:/workspace/mnb-123-no-data-flow-trigger-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/certs/dev/ " 。但是文件列表(listOfFiles)为空。

但是使用下面的代码,我可以获取“rootPath”中一个文件的内容

InputStream in = this.getClass().getResourceAsStream("/certs/"+activeProfile+"/server.cer");

            File tempFile= File.createTempFile("temporary",".cer");
            tempFile.deleteOnExit();
            try (FileOutputStream out = new FileOutputStream(tempFile)) {
                IOUtils.copy(in, out);
            }
            displayFile(tempFile);

第一个sn-p的错误是什么?如何从路径中读取所有文件?

【问题讨论】:

  • 您不能使用File.listFiles() 列出 JAR 中的文件。它只能列出文件系统上的文件。

标签: java spring-boot google-cloud-functions


【解决方案1】:

正如 Luke 在评论中指出的那样,Java File 仅处理 OS 文件系统上的“真实”文件(和目录),在 Java 7 中带有“新 I/O”(NIO)的文件系统被称为“默认”文件系统,但我们现在可以拥有其他 Java 定义的文件系统,包括一个对 jar/zip 中的条目起作用的文件系统:

    String name = ...;
    URI uri = (myclass/loader).getResource(name).toURI(); 
    // I think Paths.get using ZipFileSystemProvider ought to handle the whole URI but it doesn't, so:
    String[] spec = uri.getSchemeSpecificPart().split("!/");
    if( ! uri.getScheme().equals("jar") || spec.length != 2 || ! spec[0].startsWith("file:") ) throw new Exception ("bad URI for jar resource");
    FileSystem fs = FileSystems.newFileSystem(new URI("jar",spec[0],null), new HashMap<String,Object>());
    Files.list(fs.getPath(spec[1])) .forEach(p -> System.out.println(p.toString()));
    // instead of System.out.println can do something else, or instead of .forEach .collect into a variable
    fs.close(); // or use try-resources to close automatically

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-09
    • 2011-10-11
    • 1970-01-01
    • 2012-10-09
    • 1970-01-01
    • 2014-05-24
    • 2016-09-21
    • 2011-01-17
    相关资源
    最近更新 更多