我想使用Java在YouTube上上传视频。
一切正常,但是在应该读取用于身份验证的secrets-JSON时,我得到了Nullpointer异常。

可以请人帮我吗?

Throwable: null
java.lang.NullPointerException
at java.io.Reader.<init>(Reader.java:89)
at java.io.InputStreamReader.<init>(InputStreamReader.java:85)
at Auth.authorize(Auth.java:66)
at Upload.<init>(Upload.java:95)
at Main.main(Main.java:30)

这是代码:
public class Auth {

/**
 * Define a global instance of the HTTP transport.
 */
public static final HttpTransport HTTP_TRANSPORT = new NetHttpTransport();

/**
 * Define a global instance of the JSON factory.
 */
public static final JsonFactory JSON_FACTORY = new JacksonFactory();

/**
 * This is the directory that will be used under the user's home directory where OAuth tokens will be stored.
 */
private static final String CREDENTIALS_DIRECTORY = ".oauth-credentials";

/**
 * Authorizes the installed application to access user's protected data.
 *
 * @param scopes              list of scopes needed to run youtube upload.
 * @param credentialDatastore name of the credential datastore to cache OAuth tokens
 */
public static Credential authorize(List<String> scopes, String credentialDatastore) throws IOException {

    // Load client secrets.
    Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(JSON_FACTORY, clientSecretReader);

    // Checks that the defaults have been replaced (Default = "Enter X here").
    if (clientSecrets.getDetails().getClientId().startsWith("Enter")
            || clientSecrets.getDetails().getClientSecret().startsWith("Enter ")) {
        System.out.println(
                "Enter Client ID and Secret from https://console.developers.google.com/project/_/apiui/credential "
                        + "into src/main/resources/client_secrets.json");
        System.exit(1);
    }

    // This creates the credentials datastore at ~/.oauth-credentials/${credentialDatastore}
    FileDataStoreFactory fileDataStoreFactory = new FileDataStoreFactory(new File(System.getProperty("user.home") + "/" + CREDENTIALS_DIRECTORY));
    DataStore<StoredCredential> datastore = fileDataStoreFactory.getDataStore(credentialDatastore);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            HTTP_TRANSPORT, JSON_FACTORY, clientSecrets, scopes).setCredentialDataStore(datastore)
            .build();

    // Build the local server and bind it to port 8080
    LocalServerReceiver localReceiver = new LocalServerReceiver.Builder().setPort(8080).build();

    // Authorize.
    return new AuthorizationCodeInstalledApp(flow, localReceiver).authorize("user");
}
}

这是我得到Nullpointer Exeption的那一行:
Reader clientSecretReader = new InputStreamReader(Auth.class.getResourceAsStream("/client_secrets.json"));

非常感谢你的帮助。
希望我能尽快解决。

最佳答案

对于getResourceAsStream文档:

返回:URL对象;如果找不到具有该名称的资源,则返回null

您确定存在一个名为“/client_secrets.json”的资源吗?如果要指定相对路径,也许反斜杠不应在名称中。

10-08 07:28