当前位置: 移动技术网 > IT编程>开发语言>Java > 使用ftpClient下载ftp上所有文件解析

使用ftpClient下载ftp上所有文件解析

2019年07月22日  | 移动技术网IT编程  | 我要评论

需求:最新项目需要,写个小功能,需求就是实时下载ftp指定文件夹下的所有文件(包括子目录)到本地文件夹中,保留文件到目录路径不变。

分析:关键在于实时和下载并保持原目录。实时使用线程的定时调度完成,主要做后者,这显然要使用递归,但是ftp上的文件是不能直接得到相对路径的(恕我才疏学浅,并没有在ftpclient类中找到类似getpath()的方法),因此路径是要自己记录。总体思路有以下:

  1、得到所有路径以及子路径:递归遍历所有文件到路径。参数:ftp为ftpclient对象,path为当前的路径,patharray保存当前的路径,并将此路径集合带到主函数中去   

getpath(ftp,path,patharray);
 public static void getpath(ftpclient ftp,string path,arraylist<string> patharray) throws ioexception{
    ftpfile[] files = ftp.listfiles();
    for (ftpfile ftpfile : files) {
      if(ftpfile.getname().equals(".")||ftpfile.getname().equals(".."))continue;
      if(ftpfile.isdirectory()){//如果是目录,则递归调用,查找里面所有文件
        path+="/"+ftpfile.getname();
        patharray.add(path);
        ftp.changeworkingdirectory(path);//改变当前路径
        getpath(ftp,path,patharray);//递归调用
        path=path.substring(0, path.lastindexof("/"));//避免对之后的同目录下的路径构造作出干扰,
      }
    }
  }

  2、下载到指定的本地文件夹中,

    download(ftp, patharray, "c:\\download");程序之前出了写错误,为了排查,我把下载分成两部分,第一部分先将所有目录创建完成,在第二个for循环中进行文件的下载。参数:ftp为ftpclient,patharray为1中带出的路径集合,后面一个string为本地路径  

 public static void download(ftpclient ftp,arraylist<string> patharray,string localrootpath) throws ioexception{
    for (string string : patharray) {
      string localpath=localrootpath+string;
      file localfile = new file(localpath);
      if (!localfile.exists()) { 
        localfile.mkdirs(); 
      }
    }
    for (string string : patharray) {
      string localpath=localrootpath+string;//构造本地路径
      ftp.changeworkingdirectory(string);
      ftpfile[] file=ftp.listfiles();
      for (ftpfile ftpfile : file) {
        if(ftpfile.getname().equals(".")||ftpfile.getname().equals(".."))continue;
        file localfile = new file(localpath);
        if(!ftpfile.isdirectory()){
          outputstream is = new fileoutputstream(localfile+"/"+ftpfile.getname());
          ftp.retrievefile(ftpfile.getname(), is);
          is.close();
        }
      }
    }
  }

测试的主函数,使用的ftpclient为org.apache.commons.net.ftp.ftpclient:

 public static void main(string[] args) throws socketexception, ioexception {
    ftpclient ftp = new ftpclient();
    ftp.connect("127.0.0.1");
    ftp.login("test","test");
    int reply;
    reply = ftp.getreplycode();
    if(!ftpreply.ispositivecompletion(reply)) {
      ftp.disconnect();
      system.err.println("ftp server refused connection.");
      system.exit(1);
    }
    ftp.setbuffersize(1024);
    ftp.setfiletype(ftp.binary_file_type); 
    ftp.enterlocalpassivemode();
    string path="";
    arraylist<string> patharray=new arraylist<string>();
    getpath(ftp,path,patharray);
    system.out.println(patharray);
    download(ftp, patharray, "c:\\download");
    ftp.logout();
    ftp.disconnect();
  }

以上所述是小编给大家介绍的使用ftpclient下载ftp上所有文件,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网