InputStreamReader抛出NullPointerException [duplicate]

问题描述 投票:1回答:2

这个问题在这里已有答案:

首先,下面的代码片段是Google Cloud Project应用程序的一部分,并且在我的本地客户端上运行,该客户端是Raspberry Pi 1.为了能够将连接到Pi的传感器的数据发送到云,授权是需要。所有需要的客户机密码都存储在src / main / resources中的“client_secrets.json”中。

项目层次结构

enter image description here

尝试使用客户端机密来授权下面的代码时会抛出NullPointerException。它是“CmdLineAuthenticationProvider”类的一部分(请参阅项目层次结构)。

InputStreamReader reader = new InputStreamReader(getClass().getClassLoader().getResourceAsStream(this.clientSecretsFile));

这可能只是一个路径相关的错误,但我没有尝试解决它(我尝试调整路径,并将client_secrets.json复制到不同的位置,希望它找到它)。 “clientSecretsFile”在“RaspiApp”类中设置为“/client_secret.json”。

CmdLineAuthenticationProvider provider = new CmdLineAuthenticationProvider();

    provider.setClientSecretsFile("client_secret.json");
    provider.setScopes(SCOPES);

    // get the oauth credentials using the client secrets
    Credential credential = provider.authorize();

在我的pom.xml中,我指定了如下资源:

<sourceDirectory>src/main/java</sourceDirectory>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <targetPath>${project.build.directory}/classes</targetPath>
            <filtering>false</filtering>
            <excludes>
                <exclude>**/*.java</exclude>
            </excludes>
        </resource>
    </resources>

完整的错误代码:

java.lang.NullPointerException
    at java.io.Reader.<init>(Reader.java:78)
    at java.io.InputStreamReader.<init>(InputStreamReader.java:72)
    at de.econfood.pi.app.CmdLineAuthenticationProvider.getCredential(CmdLineAuthenticationProvider.java:102)
    at de.econfood.pi.app.CmdLineAuthenticationProvider.authorize(CmdLineAuthenticationProvider.java:64)
    at de.econfood.pi.app.RaspiApp.getSensorEndpoint(RaspiApp.java:171)
    at de.econfood.pi.app.RaspiApp.sendSensorData(RaspiApp.java:144)
    at de.econfood.pi.app.RaspiApp.onGetRecsets(RaspiApp.java:126)
    at de.econfood.pi.app.BrmReadThread.readBuffer(BrmReadThread.java:112)
    at de.econfood.pi.app.BrmReadThread.run(BrmReadThread.java:20)
    at java.lang.Thread.run(Thread.java:745)
java maven nullpointerexception google-cloud-platform inputstreamreader
2个回答
0
投票

以“/”开头的路径通常被视为绝对路径。你需要的是一个相对路径,所以省略前导“/”。


0
投票

经过两天的故障排除后,我能够自己解决这个问题......

错误的原因是POM.xml的错误配置导致client_secret.json不在它应该位于JAR中的位置,因此无法在那里找到它。

© www.soinside.com 2019 - 2024. All rights reserved.