2017-07-30 26 views
0

我正在處理一個應用程序,需要發送一個自動電子郵件按鈕點擊。我目前遇到的問題是我需要讀取json文件,並且當我將資產中存儲的json路徑傳遞到新的​​時,我得到的文件未找到Exception。這裏是我如何獲得路徑。 (想知道如果Uri.parse().toString是多餘的):FileNotFoundException當試圖閱讀JSON資產

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

,我attemping訪問JSON文件是根據我的應用程序資源文件夾Android項目目錄中的應用程序根目錄(/ app/assets /)

我不知道我在做什麼錯在這裏,但我確定它是簡單的。請幫助我指出正確的方向。

+0

你確定你的**。json文件位於'raw'資產目錄下'sample'文件夾內嗎? – 2017-07-30 06:57:33

回答

0

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

您不應使用直接文件路徑訪問資產。 文件打包並且位置將在每個設備上更改。 你需要使用一個輔助函數來獲取資產路徑

getAssets().open() 

更多信息請參見this post

1

您可以使用此函數從資產中獲取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; 
} 
+0

我能夠使用您提供的方法來構建我所需要的。謝謝。看到我在下面發佈的答案。 –

0

將文件直接保存在資產目錄中,而不是原始樣本。

然後文件的路徑會是這樣

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

希望您的問題將得到解決..