ftp工具类

来源:互联网 发布:图标设计图案软件 编辑:程序博客网 时间:2024/05/16 11:46

package com.ways.app.report.utils;


import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.sql.Date;
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;

/**
 * @author Daniel Summer(danny_xcz@163.com)
 *
 * To change the template for this generated type comment go to
 * Window>Preferences>Java>Code Generation>Code and Comments
 */
public class FTPClientUtil {
 private Log log = LogFactory.getLog(getClass());

 private FTPClient ftpClient = new FTPClient();

 public void disconnect() {
  if (ftpClient != null) {
   try {
    ftpClient.disconnect();
   } catch (IOException ex) {
    log.debug("断开连接失败!");
   }
   ftpClient = null;
  }
 }


 public String connect(String sHost, int port,String user, String password,
   String sDir) {
  try {
   ftpClient.connect(sHost);
   ftpClient.setDefaultPort(port);
   if (log.isDebugEnabled()) {
    log.debug("连接到ftp服务器:" + sHost + " 成功..开始登录");
   }
   // 登录.用户名 密码
   ftpClient.login(user, password);
   if (log.isDebugEnabled()) {
    log.debug("登录成功");
   }

  } catch (IOException e) {
   return "与FTP服务器连接失败!";
  } catch (SecurityException e) {
   return "没有权限与FTP服务器连接";
  } catch (Exception e) {
   return "没有与FTP服务器连接的权限,或用户名密码设置不正确!";
  }
  return "";
 }

 /**
  *
  * @param server
  * @param user
  * @param password
  * @param path
  * @param is
  * @param destFile
  */
 public void ftpUpload(String hostName, String userName, String password,
   String path, InputStream is, String destFile) {
  try {
   ftpClient.connect(hostName);
   if (log.isDebugEnabled()) {
    log.debug("连接到ftp服务器:" + hostName + " 成功..开始登录");
   }
   // 登录.用户名 密码
   ftpClient.login(userName, password);
   if (log.isDebugEnabled()) {
    log.debug("登录成功");
   }

   // path是ftp服务下主目录的子目录
   if (path.length() != 0)
    ftpClient.changeWorkingDirectory(path);
   // 设置传输模式
   ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);

   // 写文件
   ftpClient.storeFile(destFile, is);

  } catch (Exception e) {
   log.error(e.getMessage(), e);

  } finally {
   // 使用IO包关闭流
   // IOUtils.closeQuietly(outSteam);
   try {
    ftpClient.disconnect();
   } catch (IOException ioe) {
    log.error(ioe.getMessage(), ioe);
   }
  }
 }

 public void upload(String hostName, String userName, String password,
   String remoteDir, String zoneCode, InputStream inputStream,
   String fileName) {
  try {
   ftpClient.connect(hostName);
   if (log.isDebugEnabled()) {
    log.debug("连接到ftp服务器:" + hostName + " 成功..开始登录");
   }
   // 登录.用户名 密码
   ftpClient.login(userName, password);
   if (log.isDebugEnabled()) {
    log.debug("登录成功");
   }

   // 设置当天日期为目录名
   java.sql.Date curDay = new Date(System.currentTimeMillis());
   ftpClient.makeDirectory(zoneCode);
   // 切换到该目录
   ftpClient.changeWorkingDirectory(zoneCode);
   // 设置当天日期为目录名
   ftpClient.makeDirectory(curDay.toString());
   // 切换到该目录
   ftpClient.changeWorkingDirectory(curDay.toString());

   // 设置传输模式
   // ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
   // 写文件
   ftpClient.storeFile(fileName, inputStream);

  } catch (Exception e) {
   if (log.isDebugEnabled()) {
    log.error(e.getMessage(), e);
   }
  } finally {
   // 使用IO包关闭流
   // IOUtils.closeQuietly(outSteam);
   try {
    ftpClient.disconnect();
   } catch (IOException ioe) {
    log.error(ioe.getMessage(), ioe);
   }
  }
 }


 public String ftpDownload(String hostName,int port, String userName, String password,
   String remoteDir, OutputStream os,boolean isChange) throws Exception {
  String returnStr = "";
  try {
   returnStr = connect(hostName,port, userName, password, remoteDir);
   String forder = remoteDir.substring(0, remoteDir.lastIndexOf("/"));
   String fileName = remoteDir.substring(
     remoteDir.lastIndexOf("/") + 1, remoteDir.length());

   log.debug(forder);
   log.debug(fileName);
   // 切换到该目录
   //if(isChange){
       ftpClient.changeWorkingDirectory(forder);
       ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
   //}

   // 设置传输模式
   
   // 写文件
   ftpClient.retrieveFile(fileName, os);
  } catch (Exception e) {
   returnStr += e.getMessage();
   e.printStackTrace();
   if (log.isDebugEnabled()) {
    log.error(e.getMessage(), e);
   }
  } finally {
   try {
    disconnect();
    os.close();
   } catch (Exception ioe) {
    returnStr += ioe.getMessage();
    log.error(ioe.getMessage(), ioe);
   }
  }
  return returnStr;
 }
   
 public String ftpNewDownload(String hostName,int port, String userName, String password,
   String remoteDir, String localDir,String filename) throws Exception {
  String returnStr = "";
  OutputStream os=null;
  try {
   returnStr = connect(hostName,port, userName, password, remoteDir);
   String remoteforder = remoteDir.substring(0, remoteDir.lastIndexOf("/"));
   String [] filenames =filename.split(",") ;

   log.debug(remoteforder);
   log.debug(filename);
   // 切换到该目录
   //if(isChange){
      ftpClient.changeWorkingDirectory(remoteforder);
   // 设置传输模式
      ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
   //}
   // 写文件
            for(int i=0;i<filenames.length;i++){
             os=new java.io.FileOutputStream(localDir+filenames[i]);
             ftpClient.retrieveFile(filenames[i], os);
            }
  } catch (Exception e) {
   returnStr += e.getMessage();
   e.printStackTrace();
   if (log.isDebugEnabled()) {
    log.error(e.getMessage(), e);
   }
  } finally {
   try {
    disconnect();
    os.close();
   } catch (Exception ioe) {
    returnStr += ioe.getMessage();
    log.error(ioe.getMessage(), ioe);
   }
  }
  return returnStr;
 }
 /**
  * 判断FTP服务器上文件是否存在
  *
  * @param server
  * @param user
  * @param password
  * @param path
  * @param is
  * @param destFile
  */
 public boolean isExistFile(String hostName, String userName,
   String password, String remoteDir, String destFile) {
  try {
   ftpClient.connect(hostName);
   if (log.isDebugEnabled()) {
    log.debug("连接到ftp服务器:" + hostName + " 成功..开始登录");
   }
   // 登录.用户名 密码
   ftpClient.login(userName, password);
   if (log.isDebugEnabled()) {
    log.debug("登录成功");
   }

   ftpClient.changeWorkingDirectory(remoteDir);
   // String[] fileNames = ftpClient.listNames(remoteDir);
   FTPFile[] files = null;
   // ftpClient.changeWorkingDirectory("/");
   files = ftpClient.listFiles();

   for (int i = 0; i < files.length; i++) {
    log.debug(files[i].getName() + "?=" + destFile);
    if (files[i].getName().equals(destFile)) {
     return true;
    }
   }
 
  } catch (Exception e) {
   log.error(e.getMessage(), e);
  } finally {
   try {
    ftpClient.disconnect();
   } catch (Exception ioe) {
    log.error(ioe.getMessage(), ioe);
   }
  }
  return false;
 }

 public static void main(String[] args) {
  FTPClientUtil util = new FTPClientUtil();
  try {

   // util.ftpUpload("192.168.1.29", "sgmftp", "sgmftp#", "upload", new
   // FileInputStream(new File("D://sales.xls")), "sales.xls");

   util.ftpDownload("192.168.1.29",21, "sgmftp", "sgmftp#",
     "upload/swf/128712970.pdf", new FileOutputStream(new File(
       "D://测试w.pdf")),true);

  
  } catch (Exception e) {
   e.printStackTrace();
  }

 }
}

0 0