问题
I was trying to install client SSl cert at runtime. The certs are already packed with jar and is available in the below location
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();
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.
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?
回答1:
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
来源:https://stackoverflow.com/questions/64284646/reading-cer-files-from-jar-file-failing