- 我在ASSETS目錄下有一個xml文件(com.android.project \ assets \ xml \ file.xml)。
- 我想調用一個(下面)函數來讀取xml文件並以String的形式返回內容。
該功能要求文件的
path
作爲字符串。我不知道如何將文件的路徑作爲字符串。如果文件位於資產目錄下,如何獲取文件名作爲字符串?private String getXML(String path){ String xmlString = null; AssetManager am = this.getAssets(); try { InputStream is = am.open(path); int length = is.available(); byte[] data = new byte[length]; is.read(data); xmlString = new String(data); } catch (IOException e1) { e1.printStackTrace(); } return xmlString; }
的file.xml:
<Items>
<ItemData>
<ItemNumber>ABC</ItemNumber>
<Description>Desc1</Description>
<Price>9.95</Price>
<Weight>10.00</Weight>
</ItemData>
<ItemData>
<ItemNumber>XYZ</ItemNumber>
<Description>"Desc2"</Description>
<Price>19.95</Price>
<Weight>22.22</Weight>
</ItemData>
</Items>
問題:
我如何調用該函數
getXML(String path)
與作爲字符串參數的路徑,如果我的文件位於在\ assets \ xml \ file.xml下?最後,有沒有更好的方式來讀取XML文件作爲字符串?
謝謝!
我試圖像'/資產串/ xml/file.xml'和許多類似的字符串,像這樣使用反斜槓和正斜槓。 – wafers
看起來你需要弄清楚你的工作目錄是什麼以及你的文件的相對路徑是什麼。 –
使用:file:///android_asset/xml/file.xml –