尝试读取 json 资产时的文件未发现异常



我正在开发一个应用程序,该应用程序需要在单击按钮时发送自动电子邮件。 我目前遇到的问题是我需要读取一个 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()

有关更多信息,请参阅此帖子。

将文件直接保存在资产目录中,而不是原始样本中。

然后文件路径将是这样的

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

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

您可以使用此函数从资产中获取 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;
}

@Rohit我能够使用您提供的方法作为起点。 它唯一的问题是我使用的Gmail API需要阅读器作为其参数,而不是字符串。 这是我所做的。 而且我不再得到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;
}

相关内容

最新更新