gpt4 book ai didi

java - Android:无法读取xml

转载 作者:行者123 更新时间:2023-12-01 12:36:39 25 4
gpt4 key购买 nike

在尝试从 xml 读取时,我收到 IOException

下面是代码

File xmlFile = new File("\\assets\\data\\data.xml");
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(xmlFile);

dBuilder.parse(xmlFile) 抛出 IOException

我也尝试过 new File("/assets/data/data.xml")new File("assets/data/data.xml") 但没有用。可能的错误是什么以及如何解决?

最佳答案

您不能在运行时使用File访问assets/。您应该在运行时使用 AssetManager 访问 assets/,您可以通过 getResources().getAssets() 获取它。

有关更多信息,请参阅 Android parse XML file from Assets or internal/external storage

从 Assets 中获取 xml 为

DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(getXml(context,"data/data.xml")));
Document doc = builder.parse(is);

函数是

private String getXml(Context mContext,String path){

String xmlString = null;
AssetManager am = mContext.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;
}

关于java - Android:无法读取xml,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25520370/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com