读取位于jar中的文件作为java.io.File对象

时间:2014-05-01 20:36:50

标签: java

发布了与此相似的问题,但没有一个答案在我的案例中似乎有所帮助。 我正在编写一个使用Google凭据获取Google Apps用户的软件包。为此,我使用的是服务帐户,因此为了检索凭据,我需要提供(以及其他)p12签名文件:

   Credential credential = null;
    try {
        credential = new GoogleCredential.Builder().setTransport(httpTransport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountId(serviceAccountEmail)
                .setServiceAccountScopes(SCOPES)
                .setServiceAccountUser(serviceAccountUser)
            .setServiceAccountPrivateKeyFromP12File( java.io.File ))

最后一个函数必须接收p12签名文件的java.io.File对象。现在,整个事情都在我向其他人提供的罐子里运行,这就产生了大部分问题。无论我采取哪种方法,我都无法在jar内部运行时读取文件。在我尝试过的事情中:

return new File(GoogleUserFactory.class.getClassLoader().getResource("/" +  filePath).toURI()); 

//(我也试过没有“/”并直接使用class.GetResource())

URL url = GoogleUserFactory.class.getResource("/" + filePath);
return new File(url.getPath());  

//我也尝试了class.GetClassLoader.GetResource()...

甚至尝试将文件作为InputStreamReader读取并写入新文件(之后我将创建一个File对象并返回它),但由于我在一个jar中,我似乎无权编写一个新文件)

2 个答案:

答案 0 :(得分:0)

您可以使用.setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), SOME_INPUT_STREAM, "notasecret", "privatekey", "notasecret");建议使用here吗?

答案 1 :(得分:0)

请在没有getClassLoader()的情况下尝试。可能你试过了。但它必须奏效。如果收到NullPointerException,则filePath可能出错。

File file = new File(GoogleUserFactory.class.getResource("/" + filePath).toURI());