-2

I created a raw Android resource directory in res and added cars.json to it. It shows up on my package explorer. When I try to call

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

I get a FileNotFoundException. I've tried using simply cars.json and even the entire path to the file but I get the same results.

Any suggestions?

eyes enberg
  • 556
  • 1
  • 8
  • 30

3 Answers3

3

To get a resource from the raw directory call getResources().openRawResource(resourceName).

This will give you a InputStream

Empty2k12
  • 475
  • 12
  • 34
1

You can use this function directly:

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

You can access json data by iterating through the json object below. JSONObject obj = new JSONObject(getJsonStringFronRaw("cars.json"))

iamabhaykmr
  • 1,803
  • 3
  • 24
  • 49
-1

Retrieving resource from the raw directory can be achieved with openRawResources a sub class of getResources, this takes in a resource id (your json file) and returns a InputStream.

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

If you need more info, here is the google documention

Mitch
  • 576
  • 5
  • 11
Numan Turkeri
  • 526
  • 4
  • 18