Parsing large XML files in Android

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-11 05:29:27

问题


I am trying to parse a rather large XML file - 1MB+, but I am having some difficulties. I first tried to add the xml file to the res/xml and parse it with the XmlResourceParser, but I got an exception saying "Data exceeds UNCOMPRESS_DATA_MAX". After a bit of research I found out that the compressed files have to be uncompressed in memory before reading and that this restriction doesnt apply for raw files. However when trying to parse the xml file from the res/raw folder with the SAXParser, I get an IOException, without any message and stacktrace:

SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
xr.setContentHandler(myXMLHandler);
InputSource src = new InputSource(stream);
xr.parse(src); // IOException

From what I understand those memory restrictions do not apply to raw resources, but what is causing this exception then?

Here is the stacktrace from logcat:

11-11 23:47:50.729: WARN/System.err(4886): java.io.IOException
11-11 23:47:50.739: WARN/System.err(4886):     at android.content.res.AssetManager.readAsset(Native Method)
11-11 23:47:50.749: WARN/System.err(4886):     at android.content.res.AssetManager.access$800(AssetManager.java:36)
11-11 23:47:50.759: WARN/System.err(4886):     at android.content.res.AssetManager$AssetInputStream.read(AssetManager.java:542)
11-11 23:47:50.759: WARN/System.err(4886):     at org.apache.harmony.xml.ExpatParser.parseFragment(ExpatParser.java:504)
11-11 23:47:50.769: WARN/System.err(4886):     at org.apache.harmony.xml.ExpatParser.parseDocument(ExpatParser.java:467)
11-11 23:47:50.779: WARN/System.err(4886):     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:329)
11-11 23:47:50.790: WARN/System.err(4886):     at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:286)

回答1:


Split your file using this linux command split -l 1 main.xml

private String readTxt()
{
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    for(int J=1;J<15;J++)
    {
        int i;
        try
        {
            InputStream raw = this.getAssets().open("xa"+J);    
            i = raw.read();
            while (i != -1)
            {
                byteArrayOutputStream.write(i);
                i = raw.read();
            }
            raw.close();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

Use as string into your SAX parsing.



来源:https://stackoverflow.com/questions/4159916/parsing-large-xml-files-in-android

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!