【发布时间】:2012-10-04 07:46:10
【问题描述】:
- 我在资产目录 (com.android.project\assets\xml\file.xml) 下有 xml 文件。
- 我想调用一个(以下)函数来读取 xml 文件并将内容作为字符串返回。
-
该函数需要文件的
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; }
文件.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>
问题:
如果我的文件位于 \assets\xml\file.xml 下,我如何使用路径作为字符串参数调用函数
getXML(String path)?最后,有没有更好的方法将 XML 文件作为字符串读取?
谢谢!
【问题讨论】:
-
我尝试使用像
/assets/xml/file.xml这样的字符串以及使用反斜杠和正斜杠的许多类似字符串。 -
看起来你需要弄清楚你的工作目录是什么以及你的文件的相对路径是什么。
-
使用:file:///android_asset/xml/file.xml
-
谢谢 njzk2,
xml/file.xml工作。
标签: java android android-xml