Reading .cer files from jar file failing(从 jar 文件中读取 .cer 文件失败)
问题描述
我试图在运行时安装客户端 SSL 证书.证书已经用 jar 打包,可在以下位置获得
I was trying to install client SSl cert at runtime. The certs are already packed with jar and is available in the below location
尝试使用以下代码从上述路径读取所有可用的 .cer 文件时,失败了
While trying to read all available .cer files from the above mentioned path using below code ,it got failed
String rootPath = this.getClass().getClassLoader().getResource("certs/"+activeProfile+"/").getPath();
File folder = new File(rootPath);
File[] listOfFiles = folder.listFiles();
在调试时,我得到了rootPath";作为文件:/workspace/mnb-123-no-data-flow-trigger-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/certs/dev/".但是文件列表(listOfFiles)为空.
while debugging I am getting "rootPath" as "file:/workspace/mnb-123-no-data-flow-trigger-1.0.0-SNAPSHOT.jar!/BOOT-INF/classes!/certs/dev/" .But the list of files(listOfFiles ) is null.
但是使用下面的代码,我可以获取rootPath"中的一个文件的内容
But using the below code I am able to get the content of one of the file in "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);
第一个片段中的错误是什么?如何从路径中读取所有文件?
What is the error in the first snippet? how can I read all files from the path?
推荐答案
正如 Luke 在评论中指出的那样,Java File 只处理操作系统文件系统上的真实"文件(和目录),在 Java7 增加了新 I/O";(NIO) 被称为默认"文件系统,但我们现在可以拥有其他 Java 定义的文件系统,包括对 jar/zip 中的条目起作用的文件系统:
As Luke indicates in comment, Java File only handles 'real' files (and directories) on the OS filesystem, which in Java 7 up with "new I/O" (NIO) is called the 'default' filesystem, but we can now have other Java-defined filesystems including one that does work on entries in a 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
这篇关于从 jar 文件中读取 .cer 文件失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 jar 文件中读取 .cer 文件失败
基础教程推荐
- 从 python 访问 JVM 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
