Jar file cant find Credentials.json

Viewed 146

I'm trying to build a java project as a jar file that requires google credentials in order to run.

When i run this command:

java -jar updateservice.jar

I receive this error:

Exception in thread "main" java.io.FileNotFoundException: Resource not found: src/main/resources/credentials.json

I store the path of the credentials like this:

private static final String CREDENTIALS_FILE_PATH = "src/main/resources/credentials.json";

I use this method to retrieve credentials from the resources folder:

    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;
}

I don't understand what i need to do to avoid this error. Any help would be appreciated.

1 Answers

When maven "translates" your source code to a package, it changes the folder structure.

In a jar packaging:

  • src/main/java sources compiled go to jar's root (keeping java packages as a folder structure)
  • src/main/resources go to jar's root too.

So your file, once the jar is packaged, is in the root of the archive. Actually jar files are just zip files with a different extension, so you can use any zip manager to open it and explore it.

And to access the file do it exacrly as you are doing it, loading it as a resource from the class loader of the jar. Any class from your jar will do, as it delegates this to its class loader. Just change the path:

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