This question already has answers here:
Java Jar file: use resource errors: URI is not hierarchical

(6个答案)


3年前关闭。





我正在寻找解决问题的方法,但找不到答案。
在客户端服务器聊天应用程序中,客户端希望获取存储在Server.cer文件中的服务器公钥。

URL resource = this.getClass().getClassLoader().getResource("Server.cer");
File file = new File(resource.toURI());
FileInputStream fileInputStream = new FileInputStream(file);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
CertificateFactory cf = CertificateFactory.getInstance("X.509");
while(bufferedInputStream.available() > 0){
    certificate = cf.generateCertificate(bufferedInputStream);
}
publicKey = certificate.getPublicKey();


当我在Eclipse中运行类时,此方法工作正常,但是当将其导出为可执行jar文件时,我得到:

java.lang.IllegalArgumentException: URI is not hierarchical


您能否帮助我解决此问题,因为我需要可执行jar文件才能工作。

最佳答案

我设法解决了这个问题。这就是我做的。

    Certificate certificate = null;

    //Get server's public key which is stored in a file called Server.cer (RSA-1024 bit).
    InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("Server.cer");
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    CertificateFactory cf = CertificateFactory.getInstance("X.509");
    while(bufferedInputStream.available() > 0){
        certificate = cf.generateCertificate(bufferedInputStream);
    }
    publicKey = certificate.getPublicKey();

    bufferedInputStream.close();
    inputStream.close();

07-28 00:22