08-11
20

Caused by: org.xml.sax.SAXParseException: Premature end of file

     昨天做JDOM解析XML的时候,一直报这个错误,CPU频频出现100%现象。今天从断点追踪了下,吓了自己一跳。
   错误方法:
// 得到最大ID
    public int getMaxId(String dir) {

    int label = 0;

    FileOutputStream fo = null;

    SAXBuilder sb = new SAXBuilder();
    try {
        Document doc = sb.build(dir + Constants.ROBOT_RULE);

        Element root = doc.getRootElement();

        List list = root.getChildren("rule");

        Iterator j = this.getRules(dir).iterator();

        while (j.hasNext()) {

        for (int i = 0; i < list.size(); i++) {

            Element e = (Element) list.get(i);

            String id = e.getChild("id").getText();

            if (id != null && Integer.parseInt(id) > label)

            label = Integer.parseInt(id);
        }
                              Format format = Format.getPrettyFormat();

                               format.setIndent("  ");
                               format.setEncoding("utf-8");

                               XMLOutputter outp = new XMLOutputter(format);

                               fo = new FileOutputStream(dir + Constants.ROBOT_RULE);
        
                               outp.output(doc, fo);


        }
            } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

        if (fo != null)
            fo.close();
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

    return label;
    }



仔细一看,发现写在了迭代中,总是在输出,每读取一个节点,输出一次,还不关。


正确代码:

// 得到最大ID
    public int getMaxId(String dir) {

    int label = 0;

    FileOutputStream fo = null;

    SAXBuilder sb = new SAXBuilder();
    try {
        Document doc = sb.build(dir + Constants.ROBOT_RULE);

        Element root = doc.getRootElement();

        List list = root.getChildren("rule");

        Iterator j = this.getRules(dir).iterator();

        while (j.hasNext()) {

        for (int i = 0; i < list.size(); i++) {

            Element e = (Element) list.get(i);

            String id = e.getChild("id").getText();

            if (id != null && Integer.parseInt(id) > label)

            label = Integer.parseInt(id);
        }
        }
        Format format = Format.getPrettyFormat();

        format.setIndent("  ");
        format.setEncoding("utf-8");

        XMLOutputter outp = new XMLOutputter(format);

        fo = new FileOutputStream(dir + Constants.ROBOT_RULE);
        
        outp.output(doc, fo);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        try {

        if (fo != null)
            fo.close();
        } catch (Exception e) {
        e.printStackTrace();
        }
    }

    return label;
    }


[本日志由 blurxx 于 2009-07-01 09:18 PM 编辑]
文章来自: 本站原创
引用通告: 查看所有引用 | 我要引用此文章
Tags: Exception XML
相关日志:
评论: 0 | 引用: 0 | 查看次数: 5483
发表评论
昵 称:
密 码: 游客发言不需要密码.
内 容:
验证码: 验证码
选 项:
虽然发表评论不用注册,但是为了保护您的发言权,建议您注册帐号.
字数限制 1000 字 | UBB代码 开启 | [img]标签 关闭