设为首页 收藏本站
查看: 1133|回复: 0

[经验分享] apache FtpClient上传下载删除文件夹及文件

[复制链接]

尚未签到

发表于 2018-11-22 09:59:46 | 显示全部楼层 |阅读模式
  /*
  * 文件名:FtpUtil.java
  * 描述:FTP操作
  * 修改时间2014-08-10
  */
  import java.io.File;
  import java.io.FileInputStream;
  import java.io.FileNotFoundException;
  import java.io.FileOutputStream;
  import java.io.IOException;
  import java.text.SimpleDateFormat;
  import java.util.Arrays;
  import java.util.Calendar;
  import java.util.List;
  

  import org.apache.commons.lang.StringUtils;
  import org.apache.commons.logging.Log;
  import org.apache.commons.logging.LogFactory;
  import org.apache.commons.net.ftp.FTP;
  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;
  

  /**
  * FTP操作,主要用于上传文件、下载文件、删除文件及文件夹、获取文件加下文件名字列表
  *
  * @author
  * @version 1.0
  * @see
  * @since
  */
  public class FtpUtil
  {
  // 日志
  private static Log logger = LogFactory.getLog(FtpUtil.class);
  // FTPClient对象
  private FTPClient ftp;
  // ftp ip地址
  private String ftpServer;
  // ftp登录端口号
  private String ftpPort;
  // 登录用户名
  private String userName;
  // 登录密码
  private String password;
  public void setFtpServer(String ftpServer)
  {
  this.ftpServer = ftpServer;
  }
  public void setFtpPort(String ftpPort)
  {
  this.ftpPort = ftpPort;
  }
  public void setPassword(String password)
  {
  this.password = password;
  }
  public void setUserName(String userName)
  {
  this.userName = userName;
  }
  public FtpUtil(String ftpServer, String ftpPort, String userName, String password)
  {
  this.ftpServer = ftpServer;
  this.ftpPort = ftpPort;
  this.userName = userName;
  this.password = password;
  }
  /**
  * 连接Ftp服务器
  *
  * @return SUCCESS:成功 其他:失败信息
  * @see [类、类#方法、类#成员] Create Author:> Time: Ver:< >
  */
  public String loginToFtpServer()
  {
  if (null == ftp)
  {
  try
  {
  ftp = new FTPClient();
  // 不设端口 默认使用默认端口登录21
  if (CommonUtil.isEmpty(ftpPort))
  {
  ftp.connect(this.ftpServer);
  }
  else
  {
  ftp.connect(this.ftpServer, Integer.parseInt(ftpPort));
  }
  //下面三行代码必须要有,而且不能改变编码格式否则不能正确下载中文文件
  ftp.setControlEncoding("GBK");
  FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
  conf.setServerLanguageCode("zh");
  //验证通道连接是否建立成功(回传响应码)
  if (!FTPReply.isPositiveCompletion(ftp.getReplyCode()))
  {
  ftp.disconnect();
  logger.error("FTP连接失败,ip:" + this.ftpServer);
  return "FTP连接失败,ip:" + this.ftpServer;
  }
  //登录
  if (!ftp.login(this.userName, this.password))
  {
  logger.error("FTP登录失败,ip:" + this.ftpServer + ";userName:" + userName + ";port:" + ftpPort);
  return "FTP登录失败,ip:" + this.ftpServer + ";userName:" + userName + ";port:" + ftpPort;
  }
  }
  catch (Exception e)
  {
  logger.error("FTP连接失败", e);
  return "FTP连接失败" + e;
  }
  }
  logger.info("Ftp" + this.ftpServer + "登录成功!;port:" + ftpPort);
  return CommonProperties.SUCCESS;
  }
  /**
  * 关闭ftp连接  void
  *
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public void closeConnection()
  {
  if (null != ftp && ftp.isConnected())
  {
  try
  {
  ftp.disconnect();
  logger.info("FTP"+this.ftpServer+"连接关闭");
  }
  catch (Exception e)
  {
  logger.error("FTP连接关闭异常", e);
  }
  }
  }
  /**
  * 上传文件到ftp
  *
  * @param remotePath ftp路径
  * @param remoteName 文件名
  * @param localFile 要上传的本地文件
  * @return SECCESS:上传成功 其他:上传失败信息
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public String uploadFile(String remotePath, String localFileName)
  {
  FileInputStream in = null;
  try
  {
  // 存放在Ftp上的文件名称
  String remoteFileName = "";
  ftp.setFileType(FTP.BINARY_FILE_TYPE);
  if (CommonUtil.isEmpty(localFileName) || CommonUtil.isEmpty(remotePath))
  {
  logger.error("文件上传Ftp失败目标路径或源路径错误");
  return "文件上传Ftp失败目标路径或源路径错误";
  }
  remoteFileName = localFileName.substring(localFileName.lastIndexOf("/")+1, localFileName.length());
  // 确保文件路径存在
  ftp.makeDirectory(remotePath);
  if (!ftp.changeWorkingDirectory(remotePath))
  {
  logger.error("转至目录[" + remotePath + "]失败");
  return "转至目录[" + remotePath + "]失败";
  }
  // 上传之前先删除原来文件,防止重复对账(文件不存不报异常)
  ftp.deleteFile(remoteFileName);
  in = new FileInputStream(new File(localFileName));
  ftp.storeFile(new String(remoteFileName.getBytes("GBK"), "iso-8859-1"), in);
  }
  catch (Exception e)
  {
  logger.error("文件上传Ftp失败:", e);
  return "文件上传Ftp失败:" + e;
  }
  finally
  {
  CommonUtil.closeStream(in);
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 获取文件夹下文件名称列表
  *
  * @param remotePath 文件夹路径
  * @return List 文件名称列表
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public List getFileList(String remotePath)
  {
  try
  {
  if (ftp.changeWorkingDirectory(remotePath))
  {
  String[] str = ftp.listNames();
  if (null == str || str.length < 0)
  {
  return null;
  }
  return Arrays.asList(str);
  }
  }
  catch (IOException e)
  {
  e.printStackTrace();
  }
  return null;
  }
  /**
  * 从Ftp下载文件
  *
  * @param remotePath Ftp上文件路径
  * @param remoteFileName 远程文件名
  * @param localFileName 下载到本地文件路径(带文件名)
  * @return SUCCESS:成功 其他:失败信息
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public String download(String remotePath, String remoteFileName, String localFileName)
  {
  FileOutputStream oStream = null;
  try
  {
  // 切换到指定目录下
  if (ftp.changeWorkingDirectory(remotePath))
  {
  oStream = new FileOutputStream(new File(localFileName));
  if (!ftp.retrieveFile(remoteFileName, oStream))
  {
  logger.info("从Ftp上下载文件失败!" + remoteFileName);
  return "从Ftp上下载文件失败!" + remoteFileName;
  }
  }
  else
  {
  logger.info("对账文件下载失败,不能正常切换至目录" + remotePath + ";目录不存在!");
  return "对账文件下载失败,不能正常切换至目录" + remotePath + ";目录不存在!";
  }
  }
  catch (Exception e)
  {
  logger.info("Ftp上文件" + remoteFileName + "下载失败!", e);
  return "Ftp上文件" + remoteFileName + "下载失败!" + e;
  }
  finally
  {
  CommonUtil.closeStream(oStream);
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 删除Ftp上的文件夹 包括其中的文件
  *
  * @param client Ftp对象
  * @param pathName 文件夹路径
  * @return SUCCESS:成功 其他:失败
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public String removeDirectoryALLFile(String pathName)
  {
  try
  {
  FTPFile[] files = ftp.listFiles(pathName);
  if (null != files && files.length > 0)
  {
  for (FTPFile file : files)
  {
  if (file.isDirectory())
  {
  removeDirectoryALLFile(pathName + "/" + file.getName());
  // 切换到父目录,不然删不掉文件夹
  ftp.changeWorkingDirectory(pathName.substring(0, pathName.lastIndexOf("/")));
  ftp.removeDirectory(pathName);
  }
  else
  {
  if (!ftp.deleteFile(pathName + "/" + file.getName()))
  {
  return "删除指定文件" + pathName + "/" + file.getName() + "失败!";
  }
  }
  }
  }
  // 切换到父目录,不然删不掉文件夹
  ftp.changeWorkingDirectory(pathName.substring(0, pathName.lastIndexOf("/")));
  ftp.removeDirectory(pathName);
  }
  catch (IOException e)
  {
  logger.error("删除指定文件夹" + pathName + "失败:" + e);
  e.printStackTrace();
  return "删除指定文件夹" + pathName + "失败:" + e;
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 删除指定文件
  *
  * @param filePath 文件路径(含文件名)
  * @see [类、类#方法、类#成员]
  * @return SUCCESS:成功 其他:失败信息
  */
  public String removeFile(String filePath)
  {
  try
  {
  if (StringUtils.isNotEmpty(filePath))
  {
  if (!ftp.deleteFile(filePath))
  {
  return "删除文件" + filePath + "失败!";
  }
  }
  }
  catch (IOException e)
  {
  logger.error("删除文件失败:", e);
  e.printStackTrace();
  return "删除文件" + filePath + "失败!" + e;
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 向文件头添加合计信息
  *
  * @param localPath 目标文件所在文件夹路径
  * @param desFile 目标文件名
  * @param mergeStr 插入字符串信息
  * @return SUCCESS:成功 其他:失败信息
  */
  public static String mergeFile(String localPath, String desFile, String mergeStr)
  {
  // 向目标文件头中添加合计信息
  FileInputStream inputStream = null;
  FileOutputStream fileOutStream = null;
  try
  {
  inputStream = new FileInputStream(localPath + "/" + desFile);
  byte allBytes[] = new byte[inputStream.available()];
  inputStream.read(allBytes);
  fileOutStream = new FileOutputStream(localPath + "/" + desFile);
  fileOutStream.write(mergeStr.getBytes());
  fileOutStream.write(allBytes);
  }
  catch (IOException e)
  {
  return e.getMessage();
  }
  finally
  {
  CommonUtil.closeStream(fileOutStream);
  CommonUtil.closeStream(inputStream);
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 删除备份目录下不符合时间的文件
  *
  * @param dailyBakPath 备份目录
  * @param dailyBakDate 有效时间 1、5、9等
  * @return SUCCESS:成功 其他:失败信息
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  */
  public static String deleteFile(String dailyBakPath, String dailyBakDate)
  {
  try
  {
  // 获取符合规则的日期
  SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");
  // 当天时间
  Calendar theday = Calendar.getInstance();
  // 存放符合备份的日期时间 数组长度为备份的天数+1
  String[] dates = new String[Integer.valueOf(dailyBakDate) + 1];
  for (int i = 0; i < dates.length; i++)
  {
  dates = df.format(theday.getTime());
  // 获取上一天的时间
  theday.add(Calendar.DATE, -1);
  }
  File a = new File(dailyBakPath);
  if (!a.exists())
  {
  return dailyBakPath + "目录不存在!";
  }
  // 获取目录下所有文件
  String[] fileArr = a.list();
  // 遍历文件名称,查看是否在保留日期dates内,不在则删除
  for (int i = 0; i < fileArr.length; i++)
  {
  boolean canDele = true;
  for (int j = 0; j < dates.length; j++)
  {
  // 不删除dates内开头的文件 和 文件名包含error的文件
  if (fileArr.startsWith(dates[j]) || fileArr.contains("error"))
  {
  canDele = false;
  break;
  }
  }
  if (canDele)
  {
  deletefile(dailyBakPath + "/" + fileArr);
  }
  }
  }
  catch (Exception e)
  {
  logger.info("删除文件夹内容操作出错,请查看配置路径或保留时间是否正确!");
  return "删除文件夹内容操作出错,请查看配置路径或保留时间是否正确!";
  }
  return CommonProperties.SUCCESS;
  }
  /**
  * 根据入参,删除文件夹(下文件及文件夹)或文件
  *
  * @param delpath 文件夹路径或文件路径
  * @return boolean true:成功 false:失败
  * @see [类、类#方法、类#成员] Create Author: Time: Ver:< >
  *
  */
  public static boolean deletefile(String delpath)
  {
  try
  {
  File file = new File(delpath);
  if (file.isDirectory())
  {
  String[] filelist = file.list();
  for (int i = 0; i < filelist.length; i++)
  {
  // 递归调用
  deletefile(delpath + "\\" + filelist);
  }
  }
  // 删除
  file.delete();
  }
  catch (Exception e)
  {
  logger.error("deletefile() Exception:" + e.getMessage());
  }
  return true;
  }
  public static void main(String[] args) throws IOException
  {
  //System.out.println(deletefile("G:/Q"));
  FtpUtil ftpUtil = new FtpUtil("192.168.132.110", "21", "a", "a");
  System.out.println(ftpUtil.loginToFtpServer());
  // System.out.println(ftpUtil.removeDirectoryALLFile("/home/tbcs/zhangvb/epay/20140820"));
  // FTPClient client=new FTPClient();
  // client.connect("192.168.132.110");
  // client.login("a","a");
  // System.out.println(client.removeDirectory("/home/tbcs/zhangvb/epay/test"));
  }
  }
  





运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-638081-1-1.html 上篇帖子: apache访问提示Directory index forbidden by Options directive: /var/www/html/解决方法 下篇帖子: OS X Mavericks 10.9.4 配置 Apache+MySQL+PHP 详细图文教程
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表