Jar文件找不到Credentials.json



我正试图将一个java项目构建为一个jar文件,该文件需要谷歌凭据才能运行。

当我运行这个命令时:

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中的任何类都可以,因为它将其委托给类加载器。只需更改路径:

InputStream is = Main.class.getResourceAsStream("/credentials.json");

相关内容