FileInputStream不会抛出此类文件或目录异常 - Firebase rest API用户身份验证

时间:2016-10-16 18:59:30

标签: android firebase firebase-realtime-database firebase-authentication

我正在尝试按照本教程对Firebase实时数据库REST API进行身份验证调用:https://firebase.google.com/docs/reference/rest/database/user-auth

GoogleCredential googleCred = GoogleCredential.fromStream(new FileInputStream("cmov.json"));
GoogleCredential scoped = googleCred.createScoped(
    Arrays.asList(
      "https://www.googleapis.com/auth/firebase.database",
      "https://www.googleapis.com/auth/userinfo.email"
    )
);
scoped.refreshToken();
String token = scoped.getAccessToken();

我在Android Studio的登录活动中有这个代码,由于某种原因,我总是得到一个例外 - 打开失败:ENOENT(没有这样的文件或目录) - 当试图读取“cmov.json”时。我在我创建的“assets”文件夹中有文件,当我尝试删除文件时,我收到一个使用警告,询问我是否确定要删除该文件,所以我假设我正在阅读代码中的正确路径。为什么FileInputStream会抛出没有这样的文件或目录异常?

enter image description here

2 个答案:

答案 0 :(得分:0)

资产是开发计算机上的文件。它们不是Android设备上的文件。

Use AssetManager and open()在您的资源上打开InputStream,而不是FileInputStream

如果您开始使用设备上的实际文件,请不要只将一些字符串传递给FileFileInputStream构造函数。使用适当的方法派生internal storageexternal storage的文件系统路径。

答案 1 :(得分:0)

GoogleCredential googleCred = GoogleCredential.fromStream(new FileInputStream("cmov.json"));

您需要将其替换为以下内容:

AssetManager assetManager = getApplicationContext().getAssets();
GoogleCredential googleCred = GoogleCredential.fromStream(assetManager.open("cmov.json"));

如果该文件位于assets,即使您认为Android Studio在您输入时似乎已将其链接到该文件,因此无法找到它,因为FileInputStream意味着它在Android设备上寻找文件。您的JSON文件在技术上属于APK。

注意:我所做的是,在应用内部存储中检查该文件,如果不存在,请复制它。下次用户打开应用程序时,文件将在那里并且不会被复制。这样,访问该文件就更容易,如果需要,也可以在Android设备上使用该文件。