【问题标题】:Android Studio can't find my JSON fileAndroid Studio 找不到我的 JSON 文件
【发布时间】:2016-09-29 13:45:41
【问题描述】:

我在res 中创建了一个raw Android 资源目录并将cars.json 添加到其中。它显示在我的包资源管理器中。当我尝试打电话时

File file = new File("raw/cars.json")

我得到一个 FileNotFoundException。我试过简单地使用 cars.json 甚至文件的整个路径,但我得到了相同的结果。

有什么建议吗?

【问题讨论】:

  • 尝试过使用File file = new File("android.resource://"+getPackageName()+"/raw/equipment.json");的玩具
  • 如果您的文件名为cars.json,为什么要加载device.json?是错字吗?
  • 也试试stackoverflow.com/questions/15912825/…>.
  • 这里是类似问题的解决方案:stackoverflow.com/a/15934525/5268730

标签: java android json android-studio


【解决方案1】:

要从原始目录获取资源,请调用getResources().openRawResource(resourceName)

这会给你一个InputStream

【讨论】:

    【解决方案2】:

    你可以直接使用这个函数:

    private String getJsonStringFromRaw(filenmae)
    {
        String jsonString = null; 
        try { 
            InputStream inputStream= getAssets().open(filename); 
            int size = inputStream.available(); 
            byte[] buffer= new byte[size]; 
            inputStream.read(buffer); 
            inputStream.close(); 
            jsonString = new String(buffer, "UTF-8"); } 
        catch (IOException e) 
        { 
            e.printStackTrace(); 
            return null; 
        } 
        return jsonString; 
    }
    

    您可以通过遍历下面的 json 对象来访问 json 数据。 JSONObject obj = new JSONObject(getJsonStringFronRaw("cars.json"))

    【讨论】:

      【解决方案3】:

      从原始目录中检索资源可以通过 openRawResources 一个 getResources 的子类来实现,它接受一个资源 id(您的 json 文件)并返回一个 InputStream。

      InputStream myInput=getResources().openRawResource(R.raw.your_json);
      

      如果您需要更多信息,这里是google documention

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-09
        • 1970-01-01
        • 2020-10-24
        • 1970-01-01
        • 1970-01-01
        • 2018-05-16
        • 2014-05-05
        • 1970-01-01
        相关资源
        最近更新 更多