FileNotFound 与 .jar 和 JSSE

FileNotFound with .jar and JSSE

我正在使用 JSSE 并具有以下代码:

private static void setupServerKeystore() throws GeneralSecurityException, IOException {
        mServerKeyStore = KeyStore.getInstance( "JKS" );
        mServerKeyStore.load(new FileInputStream(iComputer.class.getClassLoader().getResource("res/server.public").getPath()), 
                            "pswd".toCharArray());
}


private static void setupClientKeyStore() throws GeneralSecurityException, IOException {
            mClientKeyStore = KeyStore.getInstance( "JKS" );
            mClientKeyStore.load(new FileInputStream(iComputer.class.getClassLoader().getResource("res/client.private").getPath()),
                                   mPassphrase.toCharArray());
}

这是我的文件夹结构:

- iComputer
   - src
        - com
            - ...
        - res
            - server.public
            - client.private

这两个 URL 在 Eclipse 中都有效,并且客户端成功执行了握手。但是,当我将其导出为 .jar 文件时,我得到一个 FileNotFoundException:

> java.io.FileNotFoundException:
> file:/Users/Zack/Downloads/iComputer.jar!/res/server.public (No
> such file or directory)

几个小时以来,我一直在努力解决这个问题,但没有成功。任何帮助将不胜感激。

好的,这就是我为解决问题所做的工作(感谢 peeskillet 提出了解决方案)。我考虑过使用 getResourceAsStream(). 的选项这在 Eclipse 中工作得很好,但问题是我在导出和 运行 jar 文件时遇到错误,"error error: sun.security.validator.ValidatorException: No trusted certificate found". 好像我是给它错误的路径。

JSSE 的 KeyStore.load() 方法将接受 any 类型的 InputStream,如文档中所示。它不一定必须成为 FileInputStream。

所以,这是我的文件结构:

- iComputer
   - src
        - com
            - ...
        - res
            - server.public
            - client.private

基于此文件结构,Eclipse 和 JAR 文件的正确工作路径是 "res/server.public"。所以,这是我对 OP 中的代码的修改:

private static void setupServerKeystore() throws GeneralSecurityException, IOException {
        mServerKeyStore = KeyStore.getInstance( "JKS" );
        mServerKeyStore.load(iComputer.class.getClassLoader().getResourceAsStream("res/server.public"), 
                            "pswd".toCharArray());
    }

private static void setupClientKeyStore() throws GeneralSecurityException, IOException {
        mClientKeyStore = KeyStore.getInstance( "JKS" );
        mClientKeyStore.load(iComputer.class.getClassLoader().getResourceAsStream("res/client.private"),
                               mPassphrase.toCharArray());
}

帮自己一个忙,将此作为放置您的 密钥文件的参考点。这将为您节省无数时间来弄清楚为什么您会得到 NullPointerExceptionFileNotFoundException.

资源不是文件,不能用FileInputStream.打开资源只是作为流获取资源,完全摆脱FileInputStream和所有名称处理。