欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Java实现FTP文件与文件夹的上传和下载

程序员文章站 2024-03-08 22:36:10
ftp 是file transfer protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于internet上的控制文件的双向传输。同时,它也是一个应用...

ftp 是file transfer protocol(文件传输协议)的英文简称,而中文简称为“文传协议”。用于internet上的控制文件的双向传输。同时,它也是一个应用程序(application)。基于不同的操作系统有不同的ftp应用程序,而所有这些应用程序都遵守同一种协议以传输文件。在ftp的使用当中,用户经常遇到两个概念:"下载"(download)和"上传"(upload)。"下载"文件就是从远程主机拷贝文件至自己的计算机上;"上传"文件就是将文件从自己的计算机中拷贝至远程主机上。用internet语言来说,用户可通过客户机程序向(从)远程主机上传(下载)文件。

首先下载了serv-u将自己的电脑设置为了ftp文件服务器,方便操作。下面代码的使用都是在ftp服务器已经创建,并且要在代码中写好ftp连接的相关数据才可以完成。

1.ftp文件的上传与下载(注意是单个文件的上传与下载)

import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.io.inputstream;
import java.io.outputstream;
import org.apache.commons.net.ftp.ftp;
import org.apache.commons.net.ftp.ftpclient;
import org.apache.commons.net.ftp.ftpfile;
import org.apache.commons.net.ftp.ftpreply;
/**
 * 实现ftp文件上传和文件下载
 */
public class ftpapche {
 private static ftpclient ftpclient = new ftpclient();
 private static string encoding = system.getproperty("file.encoding");
 /**
  * description: 向ftp服务器上传文件
  * 
  * @version1.0
  * @param url
  *   ftp服务器hostname
  * @param port
  *   ftp服务器端口
  * @param username
  *   ftp登录账号
  * @param password
  *   ftp登录密码
  * @param path
  *   ftp服务器保存目录,如果是根目录则为“/”
  * @param filename
  *   上传到ftp服务器上的文件名
  * @param input
  *   本地文件输入流
  * @return 成功返回true,否则返回false
  */
 public static boolean uploadfile(string url, int port, string username,
   string password, string path, string filename, inputstream input) {
  boolean result = false;
  try {
   int reply;
   // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接ftp服务器
   ftpclient.connect(url);
   // ftp.connect(url, port);// 连接ftp服务器
   // 登录
   ftpclient.login(username, password);
   ftpclient.setcontrolencoding(encoding);
   // 检验是否连接成功
   reply = ftpclient.getreplycode();
   if (!ftpreply.ispositivecompletion(reply)) {
    system.out.println("连接失败");
    ftpclient.disconnect();
    return result;
   }
   // 转移工作目录至指定目录下
   boolean change = ftpclient.changeworkingdirectory(path);
   ftpclient.setfiletype(ftp.binary_file_type);
   if (change) {
    result = ftpclient.storefile(new string(filename.getbytes(encoding),"iso-8859-1"), input);
    if (result) {
     system.out.println("上传成功!");
    }
   }
   input.close();
   ftpclient.logout();
  } catch (ioexception e) {
   e.printstacktrace();
  } finally {
   if (ftpclient.isconnected()) {
    try {
     ftpclient.disconnect();
    } catch (ioexception ioe) {
    }
   }
  }
  return result;
 }
 /**
  * 将本地文件上传到ftp服务器上
  * 
  */
 public void testuploadfromdisk() {
  try {
   fileinputstream in = new fileinputstream(new file("d:/test02/list.txt"));
   boolean flag = uploadfile("10.0.0.102", 21, "admin","123456", "/", "lis.txt", in);
   system.out.println(flag);
  } catch (filenotfoundexception e) {
   e.printstacktrace();
  }
 }
 /**
  * description: 从ftp服务器下载文件
  * 
  * @version1.0
  * @param url
  *   ftp服务器hostname
  * @param port
  *   ftp服务器端口
  * @param username
  *   ftp登录账号
  * @param password
  *   ftp登录密码
  * @param remotepath
  *   ftp服务器上的相对路径
  * @param filename
  *   要下载的文件名
  * @param localpath
  *   下载后保存到本地的路径
  * @return
  */
 public static boolean downfile(string url, int port, string username,
   string password, string remotepath, string filename,
   string localpath) {
  boolean result = false;
  try {
   int reply;
   ftpclient.setcontrolencoding(encoding);
   /*
    * 为了上传和下载中文文件,有些地方建议使用以下两句代替
    * new string(remotepath.getbytes(encoding),"iso-8859-1")转码。
    * 经过测试,通不过。
    */
//   ftpclientconfig conf = new ftpclientconfig(ftpclientconfig.syst_nt);
//   conf.setserverlanguagecode("zh");
   ftpclient.connect(url, port);
   // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接ftp服务器
   ftpclient.login(username, password);// 登录
   // 设置文件传输类型为二进制
   ftpclient.setfiletype(ftpclient.binary_file_type);
   // 获取ftp登录应答代码
   reply = ftpclient.getreplycode();
   // 验证是否登陆成功
   if (!ftpreply.ispositivecompletion(reply)) {
    ftpclient.disconnect();
    system.err.println("ftp server refused connection.");
    return result;
   }
   // 转移到ftp服务器目录至指定的目录下
   ftpclient.changeworkingdirectory(new string(remotepath.getbytes(encoding),"iso-8859-1"));
   // 获取文件列表
   ftpfile[] fs = ftpclient.listfiles();
   for (ftpfile ff : fs) {
    if (ff.getname().equals(filename)) {
     file localfile = new file(localpath + "/" + ff.getname());
     outputstream is = new fileoutputstream(localfile);
     ftpclient.retrievefile(ff.getname(), is);
     is.close();
    }
   }
   ftpclient.logout();
   result = true;
  } catch (ioexception e) {
   e.printstacktrace();
  } finally {
   if (ftpclient.isconnected()) {
    try {
     ftpclient.disconnect();
    } catch (ioexception ioe) {
    }
   }
  }
  return result;
 }
 /**
  * 将ftp服务器上文件下载到本地
  * 
  */
 public void testdownfile() {
  try {
   boolean flag = downfile("10.0.0.102", 21, "admin",
     "123456", "/", "ip.txt", "e:/");
   system.out.println(flag);
  } catch (exception e) {
   e.printstacktrace();
  }
 }
 public static void main(string[] args) {
  ftpapche fa = new ftpapche();
  fa.testdownfile();
  fa.testuploadfromdisk();
 }
}

2.ftp文件夹的上传与下载(注意是整个文件夹)

package ftp;
import java.io.bufferedinputstream;
import java.io.bufferedoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.filenotfoundexception;
import java.io.fileoutputstream;
import java.io.ioexception;
import java.util.timezone;
import org.apache.commons.net.ftp.ftpclient;
import org.apache.commons.net.ftp.ftpclientconfig;
import org.apache.commons.net.ftp.ftpfile;
import org.apache.commons.net.ftp.ftpreply;
import org.apache.log4j.logger;
public class ftptest_04 {
 private ftpclient ftpclient;
 private string strip;
 private int intport;
 private string user;
 private string password;
 private static logger logger = logger.getlogger(ftptest_04.class.getname());
 /* * 
  * ftp构造函数 
  */ 
 public ftptest_04(string strip, int intport, string user, string password) {
  this.strip = strip;
  this.intport = intport;
  this.user = user;
  this.password = password;
  this.ftpclient = new ftpclient();
 }
 /** 
  * @return 判断是否登入成功 
  * */ 
 public boolean ftplogin() {
  boolean islogin = false;
  ftpclientconfig ftpclientconfig = new ftpclientconfig();
  ftpclientconfig.setservertimezoneid(timezone.getdefault().getid());
  this.ftpclient.setcontrolencoding("gbk");
  this.ftpclient.configure(ftpclientconfig);
  try {
   if (this.intport > 0) {
    this.ftpclient.connect(this.strip, this.intport);
   }else {
    this.ftpclient.connect(this.strip);
   }
   // ftp服务器连接回答 
   int reply = this.ftpclient.getreplycode();
   if (!ftpreply.ispositivecompletion(reply)) {
    this.ftpclient.disconnect();
    logger.error("登录ftp服务失败!");
    return islogin;
   }
   this.ftpclient.login(this.user, this.password);
   // 设置传输协议 
   this.ftpclient.enterlocalpassivemode();
   this.ftpclient.setfiletype(ftpclient.binary_file_type);
   logger.info("恭喜" + this.user + "成功登陆ftp服务器");
   islogin = true;
  }catch (exception e) {
   e.printstacktrace();
   logger.error(this.user + "登录ftp服务失败!" + e.getmessage());
  }
  this.ftpclient.setbuffersize(1024 * 2);
  this.ftpclient.setdatatimeout(30 * 1000);
  return islogin;
 }
 /** 
  * @退出关闭服务器链接 
  * */ 
 public void ftplogout() {
  if (null != this.ftpclient && this.ftpclient.isconnected()) {
   try {
    boolean reuslt = this.ftpclient.logout();// 退出ftp服务器 
    if (reuslt) {
     logger.info("成功退出服务器");
    }
   }catch (ioexception e) {
    e.printstacktrace();
    logger.warn("退出ftp服务器异常!" + e.getmessage());
   }finally {
    try {
     this.ftpclient.disconnect();// 关闭ftp服务器的连接 
    }catch (ioexception e) {
     e.printstacktrace();
     logger.warn("关闭ftp服务器的连接异常!");
    }
   }
  }
 }
 /*** 
  * 上传ftp文件 
  * @param localfile 当地文件 
  * @param romotuploadepath上传服务器路径 - 应该以/结束 
  * */ 
 public boolean uploadfile(file localfile, string romotuploadepath) {
  bufferedinputstream instream = null;
  boolean success = false;
  try {
   this.ftpclient.changeworkingdirectory(romotuploadepath);// 改变工作路径 
   instream = new bufferedinputstream(new fileinputstream(localfile));
   logger.info(localfile.getname() + "开始上传.....");
   success = this.ftpclient.storefile(localfile.getname(), instream);
   if (success == true) {
    logger.info(localfile.getname() + "上传成功");
    return success;
   }
  }catch (filenotfoundexception e) {
   e.printstacktrace();
   logger.error(localfile + "未找到");
  }catch (ioexception e) {
   e.printstacktrace();
  }finally {
   if (instream != null) {
    try {
     instream.close();
    }catch (ioexception e) {
     e.printstacktrace();
    }
   }
  }
  return success;
 }
 /*** 
  * 下载文件 
  * @param remotefilename 待下载文件名称 
  * @param localdires 下载到当地那个路径下 
  * @param remotedownloadpath remotefilename所在的路径 
  * */ 
 public boolean downloadfile(string remotefilename, string localdires, 
   string remotedownloadpath) {
  string strfilepath = localdires + remotefilename;
  bufferedoutputstream outstream = null;
  boolean success = false;
  try {
   this.ftpclient.changeworkingdirectory(remotedownloadpath);
   outstream = new bufferedoutputstream(new fileoutputstream( 
     strfilepath));
   logger.info(remotefilename + "开始下载....");
   success = this.ftpclient.retrievefile(remotefilename, outstream);
   if (success == true) {
    logger.info(remotefilename + "成功下载到" + strfilepath);
    return success;
   }
  }catch (exception e) {
   e.printstacktrace();
   logger.error(remotefilename + "下载失败");
  }finally {
   if (null != outstream) {
    try {
     outstream.flush();
     outstream.close();
    }catch (ioexception e) {
     e.printstacktrace();
    }
   }
  }
  if (success == false) {
   logger.error(remotefilename + "下载失败!!!");
  }
  return success;
 }
 /*** 
  * @上传文件夹 
  * @param localdirectory 
  *   当地文件夹 
  * @param remotedirectorypath 
  *   ftp 服务器路径 以目录"/"结束 
  * */ 
 public boolean uploaddirectory(string localdirectory, 
   string remotedirectorypath) {
  file src = new file(localdirectory);
  try {
   remotedirectorypath = remotedirectorypath + src.getname() + "/";
   boolean makedirflag = this.ftpclient.makedirectory(remotedirectorypath);
   system.out.println("localdirectory : " + localdirectory);
   system.out.println("remotedirectorypath : " + remotedirectorypath);
   system.out.println("src.getname() : " + src.getname());
   system.out.println("remotedirectorypath : " + remotedirectorypath);
   system.out.println("makedirflag : " + makedirflag);
   // ftpclient.listdirectories();
  }catch (ioexception e) {
   e.printstacktrace();
   logger.info(remotedirectorypath + "目录创建失败");
  }
  file[] allfile = src.listfiles();
  for (int currentfile = 0;currentfile < allfile.length;currentfile++) {
   if (!allfile[currentfile].isdirectory()) {
    string srcname = allfile[currentfile].getpath().tostring();
    uploadfile(new file(srcname), remotedirectorypath);
   }
  }
  for (int currentfile = 0;currentfile < allfile.length;currentfile++) {
   if (allfile[currentfile].isdirectory()) {
    // 递归 
    uploaddirectory(allfile[currentfile].getpath().tostring(), 
      remotedirectorypath);
   }
  }
  return true;
 }
 /*** 
  * @下载文件夹 
  * @param localdirectorypath本地地址 
  * @param remotedirectory 远程文件夹 
  * */ 
 public boolean downloaddirectory(string localdirectorypath,string remotedirectory) {
  try {
   string filename = new file(remotedirectory).getname();
   localdirectorypath = localdirectorypath + filename + "//";
   new file(localdirectorypath).mkdirs();
   ftpfile[] allfile = this.ftpclient.listfiles(remotedirectory);
   for (int currentfile = 0;currentfile < allfile.length;currentfile++) {
    if (!allfile[currentfile].isdirectory()) {
     downloadfile(allfile[currentfile].getname(),localdirectorypath, remotedirectory);
    }
   }
   for (int currentfile = 0;currentfile < allfile.length;currentfile++) {
    if (allfile[currentfile].isdirectory()) {
     string strremotedirectorypath = remotedirectory + "/"+ allfile[currentfile].getname();
     downloaddirectory(localdirectorypath,strremotedirectorypath);
    }
   }
  }catch (ioexception e) {
   e.printstacktrace();
   logger.info("下载文件夹失败");
   return false;
  }
  return true;
 }
 // ftpclient的set 和 get 函数 
 public ftpclient getftpclient() {
  return ftpclient;
 }
 public void setftpclient(ftpclient ftpclient) {
  this.ftpclient = ftpclient;
 }
 public static void main(string[] args) throws ioexception {
  ftptest_04 ftp=new ftptest_04("10.0.0.102",21,"admin","123456");
  ftp.ftplogin();
  system.out.println("1");
  //上传文件夹 
  boolean uploadflag = ftp.uploaddirectory("d:\\test02", "/"); //如果是admin/那么传的就是所有文件,如果只是/那么就是传文件夹
  system.out.println("uploadflag : " + uploadflag);
  //下载文件夹 
  ftp.downloaddirectory("d:\\tm", "/");
  ftp.ftplogout();
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!