You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Studio中getResourceAsStream读取credentials.json返回null

问题描述

我正在Android Studio中开发一款可访问Google Sheets表格的应用,我的credentials.json文件内容如下:

{"client_id":[My ID], "project_id":"androidandsheets", "auth_uri":[My auth URI], "token_uri":[My token URI], "auth_provider_x509_cert_url":[URL]}

使用如下Java代码实现授权逻辑时:

private Credential authorize() throws IOException, GeneralSecurityException{
    InputStream in = SheetsAndJava.class.getResourceAsStream("credentials.json");
    GoogleClientSecrets clientSecrets = GoogleClientSecrets.load(
            GsonFactory.getDefaultInstance(),new InputStreamReader(in)
    );
    List<String> scopes = Arrays.asList(SheetsScopes.SPREADSHEETS);

    GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            GsonFactory.getDefaultInstance(),
            clientSecrets,scopes
            ).setDataStoreFactory(new FileDataStoreFactory(new File("tokens")))
            .setAccessType("offline").build();

    Credential credential = new AuthorizationCodeInstalledApp(
            flow,new LocalServerReceiver()
    ).authorize("user");

    return credential;
}

执行InputStream in = SheetsAndJava.class.getResourceAsStream("credentials.json")语句返回的输入流为null,无法读取凭证文件。

项目结构存在异常:credentials.json文件在Project视图下可见,但在Android视图下不可见,对应截图如下:
Android视图下的项目结构
Project视图下的项目结构

故障原因

getResourceAsStream()返回null的核心原因是credentials.json的存放位置错误,不在类加载路径中。Android视图不显示该文件,就是因为当前存放位置不属于Android构建系统认可的标准资源目录,IDE不会将其识别为有效项目资源,打包APK时也不会把文件打包进去,代码自然无法读取。
另外你当前使用的授权逻辑是为桌面端Java程序设计的:LocalServerReceiver会在本地开启端口接收授权回调,这套逻辑在Android系统上无法正常运行,就算解决了文件读取问题,后续授权流程也会报错。

修复方案
  • 把credentials.json移动到Android标准资源目录,二选一即可:
    • 移动到app/src/main/res/raw/目录,如果没有raw文件夹就手动新建,注意该目录下的文件名只能使用小写字母、数字、下划线,不能有大写字母和特殊字符
    • 移动到app/src/main/assets/目录,如果没有assets文件夹就手动新建,该目录对文件名限制更少
  • 替换文件读取代码,不要使用Java桌面端的类加载方式读取Android资源:
    • 如果文件放在raw目录下,使用如下代码读取:
      InputStream in = getResources().openRawResource(R.raw.credentials);
      
    • 如果文件放在assets目录下,使用如下代码读取:
      InputStream in = getAssets().open("credentials.json");
      
  • 替换桌面端授权逻辑,使用Android官方提供的Google Sign-In组件获取Sheets API访问授权,移除LocalServerReceiver相关的本地端口监听逻辑,适配Android系统的授权回调机制。

注意:不要把credentials.json存放到外部公共存储目录,避免凭证泄露造成安全风险。

内容的提问来源于stack exchange,提问作者Khushin Patel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.27 00:15:38