FTP上传下载

package com.fbank.middle.clearing.utils.ftp;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.SocketException;
import java.util.TimeZone;

@Slf4j
public class FTPCommon {
   private Logger logger = LoggerFactory.getLogger(this.getClass());
   private FTPClient ftpClient;

   private FTPModel ftpModel;
   
   public FTPCommon(FTPModel ftp) {
      // 从配置文件中读取初始化信息
      this.ftpClient = new FTPClient();
      this.ftpModel = ftp;
   }

   /**
    * 连接并登录FTP服务器
    * 
    */
   public boolean ftpLogin() {
      boolean isLogin = false;
      FTPClientConfig ftpClientConfig = new FTPClientConfig(
            FTPClientConfig.SYST_UNIX);
      ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
      this.ftpClient.setControlEncoding("GBK");
      this.ftpClient.configure(ftpClientConfig);
      try {
         if (this.ftpModel.getPort() > 0) {
            this.ftpClient.connect(ftpModel.getUrl(), ftpModel.getPort());
         } else {
            this.ftpClient.connect(ftpModel.getUrl());
         }
         // FTP服务器连接回答
         int reply = this.ftpClient.getReplyCode();
         if (!FTPReply.isPositiveCompletion(reply)) {
            this.ftpClient.disconnect();
            return isLogin;
         }
         this.ftpClient.login(this.ftpModel.getUsername(),
               this.ftpModel.getPassword());
         this.ftpClient.enterLocalPassiveMode();
         log.info("ftpModel.getRemoteDir():"+ftpModel.getRemoteDir());
         this.ftpClient.changeWorkingDirectory(this.ftpModel.getRemoteDir());
         this.ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
         isLogin = true;
      } catch (SocketException e) {
         log.error("FTP登录异常",e);
      } catch (IOException e) {
         log.error("FTP登录异常",e);
      }
      log.info("BufferSize  BufferSize={}",this.ftpClient.getBufferSize());
      this.ftpClient.setBufferSize(1024 * 2);
      this.ftpClient.setDataTimeout(2000);
      return isLogin;
   }

   /**
    * 退出并关闭FTP连接
    * 
    */
   public void close() {
      if (null != this.ftpClient && this.ftpClient.isConnected()) {
         try {
            boolean reuslt = this.ftpClient.logout();// 退出FTP服务器
            if (reuslt) {
               logger.info("退出FTP服务器 成功!");
            }
         } catch (IOException e) {
            e.printStackTrace();
         } finally {
            try {
               this.ftpClient.disconnect();// 关闭FTP服务器的连接
            } catch (IOException e) {
               logger.warn("退出FTP服务器出错!", e);
            }
         }
      }
   }

   /**
    * 检查FTP服务器是否关闭 ,如果关闭接则连接登录FTP
    * 
    * @return
    */
   public boolean isOpenFTPConnection() {
      boolean isOpen = false;
      if (null == this.ftpClient) {
         return false;
      }
      try {
         // 没有连接
         if (!this.ftpClient.isConnected()) {
            isOpen = this.ftpLogin();
         }
      } catch (Exception e) {
         e.printStackTrace();
         isOpen = false;
      }
      return isOpen;
   }

   /**
    * 设置传输文件的类型[文本文件或者二进制文件]
    * 
    * @param fileType
    *            --FTPClient.BINARY_FILE_TYPE,FTPClient.ASCII_FILE_TYPE
    */
   public void setFileType(int fileType) {
      try {
         this.ftpClient.setFileType(fileType);
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   /**
    * 下载文件
    * 
    * @param localFilePath
    *            本地文件名及路径
    * @param remoteFileName
    *            远程文件名称
    * @return
    */
   public boolean downloadFile(String localFilePath, String remoteFileName) {
      BufferedOutputStream outStream = null;
      boolean success = false;
      try {
         outStream = new BufferedOutputStream(new FileOutputStream(
               localFilePath));
         success = this.ftpClient.retrieveFile(remoteFileName, outStream);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      }catch(Exception e){
         e.printStackTrace();
      } finally {
         if (outStream != null) {
            try {
               outStream.flush();
               outStream.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return success;
   }

   /**
    * 下载文件
    * 
    * @param localFilePath
    *            本地文件
    * @param remoteFileName
    *            远程文件名称
    * @return
    */
   public boolean downloadFile(File localFile, String remoteFileName) {
      BufferedOutputStream outStream = null;
      FileOutputStream outStr = null;
      boolean success = false;
      try {
         outStr = new FileOutputStream(localFile);
         outStream = new BufferedOutputStream(outStr);
         success = this.ftpClient.retrieveFile(remoteFileName, outStr);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         try {
            if (null != outStream) {
               try {
                  outStream.flush();
                  outStream.close();
               } catch (IOException e) {
                  e.printStackTrace();
               }
            }
         } catch (Exception e) {
            e.printStackTrace();
         } finally {
            if (null != outStr) {
               try {
                  outStr.flush();
                  outStr.close();
               } catch (IOException e) {
                  e.printStackTrace();
               }

            }
         }
      }
      return success;
   }

   /**
    * 上传文件
    * 
    * @param localFilePath
    *            本地文件路径及名称
    * @param remoteFileName
    *            FTP 服务器文件名称
    * @return
    */
   public boolean uploadFile(String localFilePath, String remoteFileName) {
      BufferedInputStream inStream = null;
      boolean success = false;
      try {
         inStream = new BufferedInputStream(new FileInputStream(
               localFilePath));
         success = this.ftpClient.storeFile(remoteFileName, inStream);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (inStream != null) {
            try {
               inStream.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return success;
   }

   /**
    * 上传文件
    * 
    * @param localFilePath
    *            本地文件
    * @param remoteFileName
    *            FTP 服务器文件名称
    * @return
    */
   public boolean uploadFile(File localFile, String remoteFileName) {
      BufferedInputStream inStream = null;
      boolean success = false;
      try {
         inStream = new BufferedInputStream(new FileInputStream(localFile));
         success = this.ftpClient.storeFile(remoteFileName, inStream);
      } catch (FileNotFoundException e) {
         e.printStackTrace();
      } catch (IOException e) {
         e.printStackTrace();
      } finally {
         if (inStream != null) {
            try {
               inStream.close();
            } catch (IOException e) {
               e.printStackTrace();
            }
         }
      }
      return success;
   }

   /**
    * 检查并创建目录
    * 
    * @param dir
    */
   public void checkAndCreateDir(String dir) {

   }

   /**
    * 当前目录
    * 
    * @return
    */
   public String pwd() {
      try {
         return this.ftpClient.printWorkingDirectory();
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return "";
   }

   /**
    * 变更工作目录
    * 
    * @param remoteDir
    *            --目录路径
    */
   public void changeDir(String remoteDir) {
      try {
         this.ftpClient.changeWorkingDirectory(remoteDir);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   /**
    * 变更工作目录
    * 
    * @param remoteDir
    *            --目录路径
    */
   public void changeDir(String[] remoteDirs) {
      String dir = "";
      try {
         for (int i = 0; i < remoteDirs.length; i++) {
            this.ftpClient.changeWorkingDirectory(remoteDirs[i]);
            dir = dir + remoteDirs[i] + "/";
         }
         logger.info("变更工作目录为:" + dir);
      } catch (IOException e) {
         e.printStackTrace();
      }

   }

   /**
    * 返回上级目录
    * 
    */
   public void toParentDir(String[] remoteDirs) {
      try {
         for (int i = 0; i < remoteDirs.length; i++) {
            this.ftpClient.changeToParentDirectory();
         }
         logger.info("返回上级目录");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   public boolean createDir(String pathname) {
      try {
         return this.ftpClient.makeDirectory(pathname);
      } catch (IOException e) {
         e.printStackTrace();
      }
      return false;
   }

   public boolean createDir(String[] remoteDirs) {
      int deep = -1;
      try {
         for (int i = 0; i < remoteDirs.length; i++) {
            String node = remoteDirs[i];
            log.info("check dir node is {}",node);
            if (!this.ftpClient.changeWorkingDirectory(node)) {
               log.info("pwd is {}",this.pwd());
               log.info("make dir node is {}",node);
               if (this.ftpClient.makeDirectory(node)) {
                  this.ftpClient.changeWorkingDirectory(node);
                  continue;
               }
               log.info("make dir node error");
            }
            break;
         }
         for (int i = 0; i <= deep; i++) {
            toParentDir();
         }
      } catch (IOException e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }
      return remoteDirs.length == deep;
   }
   
   public boolean createDir2(String[] remoteDirs) {
      int deep = -1;
      try {
         this.ftpClient.changeWorkingDirectory("/");
         StringBuffer sbfDir = new StringBuffer();
         // 循环生成子目录
         for (String s : remoteDirs) {
            if("".equals(s)){
               continue;
            }
            sbfDir.append(s);
            sbfDir.append("/");
            log.info("当前目录:目录={}",this.ftpClient.printWorkingDirectory());
            // 尝试切入目录
            if (this.ftpClient.changeWorkingDirectory(s)){
               log.info("切入目录成功:目录={}",s);
               continue;
            }
            log.info("目录不存在:目录={}",s);
            log.info("创建目录开始:目录={}",s);
            if (!this.ftpClient.makeDirectory(s+"/")) {
               log.error("[失败]ftp创建目录:目录={}" , sbfDir.toString());
               return false;
            }else{
               log.info("[成功]ftp创建目录:{}" , sbfDir.toString());
               this.ftpClient.changeWorkingDirectory(s);
            }
            deep ++;
         }
         for (int i = 0; i <= deep; i++) {
            toParentDir();
         }
      } catch (Exception e) {
         log.error("ftp创建目录异常",e);
         return false;
      }
      return remoteDirs.length == deep;
   }
   
   /**
    * 返回上级目录
    * 
    */
   public void toParentDir() {
      try {
         this.ftpClient.changeToParentDirectory();
         logger.info("返回上级目录");
      } catch (IOException e) {
         e.printStackTrace();
      }
   }

   /**
    * 获得FTP 服务器下所有的文件名列表
    * 
    * @param regex
    * @return
    */
   public String[] getListFiels() {
      String files[] = null;
      try {
         files = this.ftpClient.listNames();
      } catch (IOException e) {
         e.printStackTrace();
      }
      return files;
   }

   public FTPClient getFtpClient() {
      return ftpClient;
   }

   public FTPModel getFtpModel() {
      return ftpModel;
   }

   public void setFtpModel(FTPModel ftpModel) {
      this.ftpModel = ftpModel;
   }

}

转载于:https://my.oschina.net/u/3855710/blog/3014601

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值