使用SAXReader读取ftp服务器上的xml文件(原创)

根据项目需求,需要监测ftp服务器上的文件变化情况,并将新添加的文件读入项目系统(不需要下载)。

spring配置定时任务就不多说了,需要注意的一点就是,现在的项目很多都是通过maven构建的,分好多子项目,通过pom互相依赖,定时任务的配置文件需要放到tomcat等容器发布的工程下,而不要放到任务所在的子项目里面,bean的class属性是可以通过项目依赖读取到其他子项目里面的class的,而且任务类需要有构造方法,涉及到spring架构的bean的知识,说的有点多了。。。

==================================================================

下面进入正题-_-!

1、SAXReader类中的几个read方法如图:

FTP服务器上的文件都是FTPFile类型,read(File)方法必然不可用,至于可不可以将FTPFile转换为File,没有过多研究;使用read(URL)方法,URL填入文件对应的ftp地址时报错(不可用的用户名密码),由于这不是用ftpclient去读ftp文件,没有登录服务器,没有权限是必然的,至于怎么用SAXReader登录ftp服务器去读取ftpFile,没有过多研究。这两方面以后有时间再回头调查一下。

read(ImputStream)方法不管看起来还是用起来,都是可行的。。。

    /**
     * 解析xml文件,读取xml中每个标签内的信息
     * @param fPath ftp文件,例如:a.xml
     * @param eName xml标签,例如:"//sciencereading_book:id"
     * @return xml标签中的内容
     */
    public String parseXML(FTPFile fPath, String eName) {

        String rtn = "";
        Document document = null;
        InputStream ins = null;
        try {
            SAXReader saxreader = new SAXReader();
            ins = this.ftp.retrieveFileStream(fPath.getName());
            document = saxreader.read(ins);
            List list_1 = document.selectNodes(eName);
            for (Iterator iter = list_1.iterator(); iter.hasNext();) {
                Element element = (Element) iter.next();
                rtn = element.getText();
            }
            ftp.getReply();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        } finally {
            if(ins != null){
                try {
                    ins.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return rtn;
    }
}

特别说明:ftp.getReply(); 一定不能忘记,把接下来的226消费掉,如果没有写,下一次this.ftp.retrieveFileStream()返回的InputStream对象会一直为null!!!

log如下:

如果不写,则只有     RETR B97870302061380003600.xml      200 Port command successful.(没有将文件读入输入流)

原文地址:https://www.cnblogs.com/superJF/p/4633688.html