尝试读取 json 资产时出现 FileNotFoundException

FileNotFoundException when attempting to read json asset

我正在开发一款需要在点击按钮时自动发送电子邮件的应用程序。我目前遇到的问题是我需要读取一个 json 文件,当我将存储在资产中的 json 的路径传递到一个新的 FileReader() 中时,我得到一个文件未找到Exception。这是我获得路径的方式。 (想知道 Uri.parse().toString 是否多余):

private static final String CLIENT_SECRET_PATH = 
        Uri.parse("file:///android_asset/raw/sample/***.json").toString()

这是我将其传递给的方法:

sClientSecrets = GoogleClientSecrets
      .load(jsonFactory, new FileReader(CLIENT_SECRET_PATH));

我正在尝试访问的 json 文件位于 android 项目目录 (/app/assets/)

应用程序根目录下的我的应用程序资产文件夹中

我不确定我在这里做错了什么,但我确定这很简单。请帮我指明正确的方向。

您不应使用直接文件路径访问资产。 文件已打包,并且每个设备上的位置都会发生变化。 您需要使用辅助函数来获取资产路径

getAssets().open()

有关详细信息,请参阅 this post

您可以使用此函数从资产中获取 JSON 字符串并将该字符串传递给 FileReader。

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
}
return json;
}

将您的文件直接保存在 assets 目录中,而不是 raw-sample。

然后文件路径就是这样

private static final String CLIENT_SECRET_PATH = 
    Uri.parse("file:///android_asset/***.json").toString()

希望你的问题能得到解决..

@Rohit 我能够使用您提供的方法作为起点。唯一的问题是我使用的 gmail api 需要 Reader 作为参数,而不是字符串。这就是我所做的。我不再收到 filenotfoundexception。非常感谢。

public InputStreamReader getJsonStreamReader(String file){
    InputStreamReader reader = null;
    try {
        InputStream in = getAssets().open(file);
        reader = new InputStreamReader(in);
    }catch(IOException ioe){
        Log.e("launch", "error : " + ioe);
        }
    return reader;
}