Reading .cer files from jar file failing

后端 未结 1 533
清酒与你
清酒与你 2021-01-23 15:22

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

1条回答
  •  粉色の甜心
    2021-01-23 15:55

    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());
        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
    

    0 讨论(0)
提交回复
热议问题