简体   繁体   English

以java.io.File对象的形式读取位于jar中的文件

[英]Reading a file located in a jar as java.io.File object

Similar questions to this one were posted, but none of the answers seems to help in my case. 发布了与此问题类似的问题,但对我而言,所有答案似乎都无济于事。 I am writing a package that uses Google's credentials to obtain Google Apps users. 我正在编写一个使用Google凭据获取Google Apps用户的软件包。 For this, I am using a service account, and so in order to retrieve the credentials, I need to provide (among others) a p12 signature file: 为此,我正在使用服务帐户,因此为了检索凭据,我需要(除其他外)提供一个p12签名文件:

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

The last function must receive a java.io.File object of the p12 signature file. 最后一个函数必须接收p12签名文件的java.io.File对象。 Now, this whole thing runs inside a jar I am providing to others, and that creates most of the problems. 现在,这整个过程都在我提供给其他人的罐子中运行,这造成了大多数问题。 I couldn't read the file when running inside the jar no matter which approach I took. 无论我采用哪种方法,在jar中运行时我都无法读取文件。 Among things I tried: 在我尝试过的事情中:

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

// (I also tried without the "/" and using class.GetResource() directly) //(我也尝试了不使用“ /”并直接使用class.GetResource()的方法)

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

// I also tried class.GetClassLoader.GetResource()... //我也尝试过class.GetClassLoader.GetResource()...

Even tried to read the file as a InputStreamReader and write to a new File (which after I will create a File object for and return it), but since I am in a jar, I cannot seem to have permissions to write a new file) 甚至尝试将文件作为InputStreamReader读取并写入新文件(在为该文件创建一个File对象并返回它之后),但是由于我在jar中,因此似乎没有写一个新文件的权限。

可能是你可以使用.setServiceAccountPrivateKey(SecurityUtils.loadPrivateKeyFromKeyStore(SecurityUtils.getPkcs12KeyStore(), SOME_INPUT_STREAM, "notasecret", "privatekey", "notasecret");作为建议在这里

Please try without getClassLoader(). 请尝试不使用getClassLoader()。 Probably you tried it. 可能您尝试过了。 but it must work. 但它必须工作。 if you receive NullPointerException filePath can be wrong. 如果收到NullPointerException,则filePath可能是错误的。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM