java ftp

jar依赖commons-net-3.6.jar


package gtk.util;



import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.StringTokenizer;


import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;


public class FTPUtil
{
  private String strIp;
  private int intPort;
  private String user;
  private String password;
  private static final Log logger = LogFactory.getLog(FTPUtil.class);


  public FTPUtil(String strIp, int intPort, String user, String Password)
  {
    this.strIp = strIp;
    this.intPort = intPort;
    this.user = user;
    this.password = Password;
  }
  
  
  /**
   * 连接FTP Server
   * @throws IOException
   */
  public FTPClient connect(){        
      FTPClient client = new FTPClient();
      try{
          //连接FTP Server
          client.connect(this.strIp, this.intPort);
          //登陆
          client.login(this.user, this.password);
          //设置文件格式
          client.setFileType(FTPClient.BINARY_FILE_TYPE);
          //获取FTP Server 应答
          int reply = client.getReplyCode();
          if(!FTPReply.isPositiveCompletion(reply)){
              client.disconnect();
              return null;
          }
          logger.info("******连接到FTP:"+strIp+":"+intPort);
      }catch(IOException e){
          return null;
      }
      return client;
  }
  /**
   * 切换工作目录,远程目录不存在时,创建目录
   * @param client
   * @throws IOException
   */
  private boolean mkDir(FTPClient client,String ftpPath,String seporator) throws IOException{
 
      StringTokenizer token = new StringTokenizer(ftpPath,seporator);
      String tmp="";
      while(token.hasMoreTokens()){
          String path = token.nextToken();
          tmp = tmp+seporator+path;
          if((!client.changeWorkingDirectory(tmp))) {
          if((!client.makeDirectory(path))) return false;
          }
          if((!client.changeWorkingDirectory(tmp))) return false;
      }
      logger.info(">>>创建目录:"+ftpPath);
      return true;
  }
  /**
   * 断开FTP连接
   * @param ftpClient
   * @throws IOException
   */
  public void close(FTPClient ftpClient) throws IOException{
      if(ftpClient!=null && ftpClient.isConnected()){
          ftpClient.logout();
          ftpClient.disconnect();
      }
      logger.info("******断开FTP连接:"+strIp+":"+intPort);
  }
  
 /**
  * 
  * @param ftpClient  
  * @param localFile 本地文件
  * @param targetName 上传后文件名——不传值默认本地名
  * @param ftpPath ftp存储位置
  * @return
  */
  public boolean upload(FTPClient ftpClient,String localFile,String targetName,String ftpPath){
      File file = new File(localFile);
      //设置上传后文件名
      if(targetName==null||"".equals(targetName))
          targetName = file.getName();
      FileInputStream fis = null;
      try{
          //开始上传文件
          fis = new FileInputStream(file);
          if((!ftpClient.changeWorkingDirectory(ftpPath))) {
          logger.error(String.format(">>>ftp 切换到工作目录(%s)失败:",ftpPath));
          return false;
          }
          logger.info(">>>开始上传文件:"+file.getName());
          long now = System.currentTimeMillis();
          boolean ok = ftpClient.storeFile(new String(targetName.getBytes("UTF-8"), "ISO-8859-1"), fis);
          if(ok){//上传成功
              long times = System.currentTimeMillis() - now;
              logger.info(String.format(">>>上传成功:大小:%s,上传时间:%d秒", formatSize(file.length()),times/1000));
          }else//上传失败
              logger.info(String.format(">>>上传失败:大小:%s", formatSize(file.length())));
      }catch(IOException e){
          System.err.println(String.format(">>>上传失败:大小:%s", formatSize(file.length())));
          e.printStackTrace();
          return false;
      }finally{
          try{
              if(fis!=null)
                  fis.close();
          }catch(Exception e){}
      }
      return true;
  }
  /**
   * 
   * @param ftpClient
   * @param ftpPath  ftp位置
   * @param localPath  下载到本地位置
   * @return
   */
  public int download(FTPClient ftpClient,String ftpPath,String localPath){
  try {
    if((!ftpClient.changeWorkingDirectory(ftpPath))) {
        logger.error(String.format(">>>ftp 切换到工作目录(%s)失败:",ftpPath));
        return 0;
        }
logger.info(">>>切换到目录:"+ftpPath);
      } catch (IOException e1) {
logger.error(this.getClass().getName()+".download()错误");
e1.printStackTrace();
      }
      FTPFile[] ftpFiles = null;
      try{
          ftpFiles = ftpClient.listFiles();
          if(ftpFiles==null||ftpFiles.length==0)
              return 0;
      }catch(IOException e){
          return 0;
      }
      File dir = new File(localPath);
      if(!dir.exists())
          dir.mkdirs();
      int count = 0;
      for(int i=0;i<ftpFiles.length;i++){
          FileOutputStream fos = null;
          try{
              String name = ftpFiles[i].getName();
              name = new String(name.getBytes("ISO-8859-1"),"UTF-8");
              fos = new FileOutputStream(new File(dir.getAbsolutePath()+File.separator+name));
              logger.info(">>>开始下载文件:"+name);


              long now = System.currentTimeMillis();
              boolean ok = ftpClient.retrieveFile(new String(name.getBytes("UTF-8"),"ISO-8859-1"), fos);
              if(ok){//下载成功
                  long times = System.currentTimeMillis() - now;
                  logger.info(String.format(">>>下载成功:大小:%s,上传时间:%d秒", formatSize(ftpFiles[i].getSize()),times/1000));
                  count++;
              }else{
                  logger.info(">>>下载失败");
              }
          }catch(IOException e){
              System.err.println(">>>下载失败");
              e.printStackTrace();
          }finally{
              try{
                  if(fos!=null)
                      fos.close();
              }catch(Exception e){}
          }
      }
      return count;
  }
  
 
  private String formatSize(long size){
  DecimalFormat DF = new DecimalFormat("#.##");
      if(size<1024){
          return size + " B";
      }else if(size<1024*1024){
          return size/1024 + " KB";
      }else if(size<1024*1024*1024){
          return (size/(1024*1024)) + " MB";
      }else{
          double gb = size/(1024*1024*1024);
          return DF.format(gb)+" GB";
      }
  }


  public boolean rmFile(FTPClient ftpClient, String srcFname)
  {
      try {
      return  ftpClient.deleteFile(new String(srcFname.getBytes("UTF-8"),"ISO-8859-1"));
      } catch (IOException e) {
        e.printStackTrace();
      }


    return false;
  }


  public boolean iterateRmFile(FTPClient ftpClient ,String ftpPath,String separator)
    throws IOException
  {
    FTPFile[] arrayOfFTPFile1;
    FTPFile[] files = ftpClient.listFiles(ftpPath);
    boolean flag = false;
    int j = (arrayOfFTPFile1 = files).length; 
    for (int i = 0; i < j; ++i) {
    FTPFile f = arrayOfFTPFile1[i];
    String path = ftpPath + separator + f.getName();
    if (f.isFile()){
    if (ftpClient.deleteFile(path))
    logger.info(new String(f.getName().getBytes("ISO-8859-1"),"UTF-8") + "删除成功!");
    }else if (f.isDirectory())
    iterateRmFile(ftpClient,path,separator);


    }
    FTPFile[] files2 = ftpClient.listFiles(ftpPath);
    if (files2.length == 0)
      flag = ftpClient.removeDirectory(ftpPath);
    else
      flag = false;


    return flag;
  }


  public static void main(String[] args) throws IOException {
    FTPUtil ftputil = new FTPUtil("10.10.1.22", 21, "", "");
    FTPClient ftpClient = ftputil.connect();
    ftputil.connect();
//    System.out.println(ftputil.download(ftpClient, "/SpecDoc/RW0000004246/", "D:\\test"));
    ftputil.mkDir(ftpClient, "/SpecDoc/test1","/");
    ftputil.upload(ftpClient, "D:\\test\\MPL Series.pdf", "火狐1.pdf", "/SpecDoc/test1");
    ftputil.upload(ftpClient, "D:\\test\\MPL Series.pdf", "火狐2.pdf", "/SpecDoc/test1");
    ftputil.upload(ftpClient, "D:\\test\\MPL Series.pdf", "火狐3.pdf", "/SpecDoc/test1");
    ftputil.upload(ftpClient, "D:\\test\\MPL Series.pdf", "火狐4.pdf", "/SpecDoc/test1");
    System.out.println(ftpClient.changeWorkingDirectory("/SpecDoc/test1"));
    System.out.println(ftputil.rmFile(ftpClient, "火狐1.pdf"));
    System.out.println(ftputil.iterateRmFile(ftpClient, "/SpecDoc/test1", "/"));
    ftputil.close(ftpClient);
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值