【问题标题】:FileNotFoundException when attempting to read json asset尝试读取 json 资产时出现 FileNotFoundException
【发布时间】:2017-07-30 06:31:25
【问题描述】:

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

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

【问题讨论】:

  • 您确定您的 **.json 文件位于资产目录中 'raw' 下的 'sample' 文件夹中吗?

标签: java android json filenotfoundexception


【解决方案1】:

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

getAssets().open()

更多信息请参见this post

【讨论】:

    【解决方案2】:

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

    然后文件路径会是这样的

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

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

    【讨论】:

      【解决方案3】:

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

      【讨论】:

      • 我能够使用您提供的方法来构建我需要的东西。谢谢你。请参阅我在下面发布的答案。
      【解决方案4】:

      @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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-02
        • 2015-08-13
        • 2019-07-01
        相关资源
        最近更新 更多