2016-09-29 178 views
-1

我在res中創建了一個raw Android資源目錄,並在其中添加了cars.json。它顯示在我的包瀏覽器上。當我嘗試調用Android Studio無法找到我的JSON文件

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

我得到一個FileNotFoundException異常。我試過簡單地使用cars.json,甚至整個文件的路徑,但我得到了相同的結果。

有什麼建議嗎?

+0

玩具嘗試使用'File file = new File(「android.resource://」+ getPackageName()+「/raw/equipment.json」 );' –

+0

如果你的文件名爲cars.json,你爲什麼要加載equipment.json?這是一個錯字嗎? – Ben

+0

嘗試。 –

回答

3

要從原始目錄獲取資源,請致電getResources().openRawResource(resourceName)

這會給你一個InputStream

-1

嗨, 我用的InputStream這個session.Dontwork你的。

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

然後你可以使用任何where.it就是這麼簡單

1

您可以直接使用此功能:

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」))

相關問題