FileInputStream fis = new FileInputStream(f);
SAXParserFactory factory = SAXParserFactory.newInstance();
factory.setNamespaceAware(true);
SAXParser saxParser = factory.newSAXParser();//sax解析的,直接继承DefaultHandler
MyHandler1 handler = new MyHandler1(fis);
saxParser.parse(fis, handler);在handler的事件处理中,我如何才能获取fis流的位置啊?
我试着将fis传入到handler里面,调用available函数,一开始输出一个有效数字,再之后就全部是0了,有哪位有办法解决这个问题的?感激不尽!
如果能够有其他方法,既能进行sax解析xml文件,又能够定位文件流的位置也可以。

解决方案 »

  1.   

    DefaultHanlder所继承的接口ContentHandler中有一个方法public void setDocumentLocator(Locator locator)这个方法是推荐SAX解析器来调用的(但并非必须),因此,如果你所用的SAX解析器支持,它会在调用你的Handler的任何方法之前,尝试调用此方法,
    因此,你可以重载此方法,看能不能拿到一个location,只要拿到locator,就可以获得当前的行、列。如果没有,可以换一家XML类库试试。
    ---------------
    public void setDocumentLocator(Locator locator)Receive an object for locating the origin of SAX document events. 
    SAX parsers are strongly encouraged (though not absolutely required) to supply a locator: if it does so, it must supply the locator to the application by invoking this method before invoking any of the other methods in the ContentHandler interface.The locator allows the application to determine the end position of any document-related event, even if the parser is not reporting an error. Typically, the application will use this information for reporting its own errors (such as character content that does not match an application's business rules). The information returned by the locator is probably not sufficient for use with a search engine.Note that the locator will return correct information only during the invocation of the events in this interface. The application should not attempt to use it at any other time.
    Parameters:
    locator - An object that can return the location of any SAX document event.
    See Also:
    Locator
      

  2.   

    我试过这种方法,能获取到locator,但是似乎意义不大,因为获取到xml文件的行、列信息,我还是得不到文件流的位置(变化检测算法中需要定位流的位置,后续算法需要用流的索引删除相同的文档内容,从而得到文件的变化内容),还是很感激你。
      

  3.   

    你把xml文件先解析成一个文件类型,再把这个文件类型做为参数传到你的handler里面就可以了。
      

  4.   

    楼上的方法也试过了:File f = new File("test.xml");
    ...
    MyHandler1 handler = new MyHandler1(f); 
    ...
    handler触发事件时,对file进行处理,还是不能得到流的位置啊。
      

  5.   

    fis.getChannel(),行不行?不知道你拿到文件位置要做什么?
      

  6.   

    我直接说我想实现的功能吧,我需要检测xml文件的变化,我先利用sax遍历整个文档,在这个过程中获取元素在流里面的开始位置,长度以及hash值,当第二次遍历xml文件时候,如果元素的hash值相同,则需要跳过元素,不做任何处理,知道最后,留下来的就是变化的部分。所以需要在sax解析时获取到流的位置。似乎没有fis.getChannel()这个方法哦!
      

  7.   

    那你这个需求我觉得用Locator可以实现吧。你用长度和Hash值决定元素是否变化,而用Locator得到的 行、列,不一样可以表示标签有没有发生变化吗?
    不好意思,fis.getChannel不是public方法。