FtpHelper.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. package com.hz.employmentsite.util;
  2. import org.apache.commons.net.ftp.FTPClient;
  3. import org.apache.commons.net.ftp.FTPConnectionClosedException;
  4. import org.apache.commons.net.ftp.FTPReply;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.beans.factory.annotation.Autowired;
  8. import org.springframework.context.annotation.Scope;
  9. import org.springframework.stereotype.Component;
  10. import com.hz.employmentsite.AppConfig;
  11. @Scope(value = "request",proxyMode=org.springframework.context.annotation.ScopedProxyMode.TARGET_CLASS)
  12. @Component
  13. public class FtpHelper {
  14. @Autowired
  15. AppConfig appConfig;
  16. private final Logger logger;
  17. public FtpHelper(){
  18. logger = LoggerFactory.getLogger(this.getClass());
  19. }
  20. /**
  21. * 连接FTP
  22. * @throws FTPConnectionClosedException
  23. * @throws Exception
  24. */
  25. public void connectToServer(FTPClient ftpClient) throws FTPConnectionClosedException,Exception{
  26. if (!ftpClient.isConnected()) {
  27. int reply;
  28. try {
  29. ftpClient.setControlEncoding("utf-8");
  30. ftpClient.connect(appConfig.ftpHost,appConfig.ftpPort);
  31. ftpClient.login(appConfig.ftpUser,appConfig.ftpPwd);
  32. reply = ftpClient.getReplyCode();
  33. if (!FTPReply.isPositiveCompletion(reply)) {
  34. ftpClient.disconnect();
  35. logger.info("connectToServer FTP server refused connection.");
  36. }
  37. ftpClient.enterLocalPassiveMode();
  38. }catch(FTPConnectionClosedException ex){
  39. logger.error("服务器:IP:"+appConfig.ftpHost+"没有连接数!there are too many connected users,please try later", ex);
  40. throw ex;
  41. }catch (Exception e) {
  42. logger.error("登录ftp服务器【"+appConfig.ftpHost+"】失败", e);
  43. throw e;
  44. }
  45. }
  46. }
  47. /**
  48. * 关闭FTP连接
  49. */
  50. public void closeConnect(FTPClient ftpClient) {
  51. try {
  52. if (ftpClient != null && ftpClient.isConnected()) {
  53. ftpClient.logout();
  54. ftpClient.disconnect();
  55. }
  56. } catch (Exception e) {
  57. logger.error("ftp连接关闭失败!", e);
  58. }
  59. }
  60. }