我正在尝试将 java 项目构建为 jar 文件,需要 google 凭据才能运行。
当我运行此命令时:
java -jar updateservice.jar
我收到此错误:
Exception in thread "main" java.io.FileNotFoundException: Resource not found: src/main/resources/credentials.json
我像这样存储凭据的路径:
private static final String CREDENTIALS_FILE_PATH = "src/main/resources/credentials.json";
我使用此方法从资源文件夹中检索凭据:
private static Credential getCredentials(final NetHttpTransport HTTP_TRANSPORT) throws IOException {
// Load client secrets.
InputStream in = Main.class.getResourceAsStream(CREDENTIALS_FILE_PATH);
if (in == null) {
throw new FileNotFoundException("Resource not found: " + CREDENTIALS_FILE_PATH);
}
GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, new InputStreamReader(in));
// Build flow and trigger user authorization request.
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, SCOPES)
.setDataStoreFactory(new FileDataStoreFactory(new java.io.File(TOKENS_DIRECTORY_PATH)))
.setAccessType("offline")
.build();
LocalServerReceiver receiver = new LocalServerReceiver.Builder().setPort(8888).build();
Credential credential = new AuthorizationCodeInstalledApp(flow, receiver).authorize("user");
//returns an authorized Credential object.
return credential;
}
我不明白我需要做什么才能避免此错误。任何帮助将不胜感激。
最佳答案
当 maven 将源代码“翻译”为包时,它会更改文件夹结构。
在 jar
包装中:
src/main/java
编译后的源文件转到 jar 的根目录(将 java 包保留为文件夹结构)src/main/resources
也转到 jar 的根目录。
因此,一旦 jar 被打包,您的文件就位于存档的根目录中。实际上,jar 文件只是具有不同扩展名的 zip 文件,因此您可以使用任何 zip 管理器打开它并浏览它。
要访问该文件,请按照您正在执行的操作进行操作,将其作为资源从 jar 的类加载器加载。 jar 中的任何类都可以,因为它将它委托(delegate)给它的类加载器。只需更改路径即可:
InputStream is = Main.class.getResourceAsStream("/credentials.json");
关于java - Jar 文件找不到 Credentials.json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70788083/