ftp upload and download tools

package com.cmbc.runbatch.utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FtpUtil {
 private static final Logger logger = LoggerFactory.getLogger(FtpUtil.class);

 private static final int BYTE_SIZE = 1024;

 /**
  * ftp server address
  */
 private String host;
 /**
  * ftp port
  */
 private int port;
 /**
  * ftp username
  */
 private String userName;
 /**
  * ftp user
  */
 private String password;
 /**
  * The path to download the file from FTP
  */
 private String downloadPath;
 /**
  * The path to upload files to FTP
  */
 private String uploadPath;

 /**
  * Connect to FTP server
  *
  * @return ftpClient ftp server connection object
  */
 private FTPClient connectFTPClient() {
  FTPClient ftpClient = new FTPClient();

  try {
   ftpClient = new FTPClient();
   ftpClient.connect(host, port);// Connect to FTP server
   ftpClient.login(userName, password);// Login to FTP server

   ftpClient.setControlEncoding("UTF-8");
   ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
   ftpClient.enterLocalPassiveMode();

   logger.info("连接TFP,host={},port={},userName={},passWord={}", host, port, userName, password);

   if (! FTPReply.isPositiveCompletion (ftpClient.getReplyCode ())) {
    logger.error("Failed to connect to FTP, wrong username or password!");
    ftpClient.disconnect();
   } else {
    logger.info("FTP connection is successful!");
   }
  } catch (Exception e) {
   logger.error("error:", e);
  }
  return ftpClient;
 }

 /**
  * Batch download files from ftp server
  *
  * @param localPath
  * The local save path of the downloaded file
  * @param ftpFileNames
  * List of files to download
  *
  * @return true download successful false download failed
  */
 public boolean downloadFilesFromFTP(String localPath, String[] ftpFileNames) {

  FTPClient ftpClient = null;
  OutputStream os = null;
  InputStream in = null;

  boolean isDownloadSuccess = false;

  try {
   ftpClient = connectFTPClient();
   if (ftpClient == null) {
    return false;
   }
   if (!ftpClient.changeWorkingDirectory(downloadPath)) {
    logger.error("FTP directory switch failed");
    return false;
   }

   for (String ftpFileName : ftpFileNames) {
    logger.info("FTP download path{},file{}", downloadPath, ftpFileName);
    // Determine if the file exists on the FTP
    in = ftpClient.retrieveFileStream(ftpFileName);
    if (in == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
     logger.error("File on FTP server" + downloadPath + ftpFileName + "Does not exist!");
     return false;
    }
    ftpClient.completePendingCommand();
    if (in != null) {
     in.close();
    }

    // download file from ftp
    File localFile = new File(localPath + ftpFileName);
    if (localFile.exists()) {
     localFile.delete();
    } else {
     if (!localFile.getParentFile().exists()) {
      localFile.getParentFile().mkdirs();
     }
    }

    localFile.createNewFile();

    os = new FileOutputStream(localFile);
    if (!ftpClient.retrieveFile(localFile.getName(), os)) {
     logger.error("File" + downloadPath + ftpFileName + "Download failed!");
     return false;
    }
   }

   ftpClient.logout();
   isDownloadSuccess = true;
  } catch (Exception e) {
   logger.error("error", e);
  } finally {
   if (os != null) {
    try {
     os.flush();
     os.close();
    } catch (IOException e) {
     logger.error("FileOutputStream failed to close:", e);
    }
   }

   if (in != null) {
    try {
     in.close();
    } catch (IOException e) {
     logger.error("FileInputStream failed to close:", e);
    }
   }

   if (ftpClient != null && ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException e) {
     logger.error("FTP connection failed to close:", e);
    }

   }
  }
  return isDownloadSuccess;
 }

 /**
  * Batch upload files to ftp server
  *
  * @param localFile
  * Array of uploaded files
  * @return true upload successful false upload failed
  */
 public boolean uploadFilesToFTP(File[] localFiles) {
  FileInputStream in = null;
  FTPClient ftpClient = null;

  ByteArrayInputStream byteIn = null;
  try {
   ftpClient = connectFTPClient();
   if (ftpClient == null) {
    return false;
   }

   if (!ftpClient.changeWorkingDirectory(uploadPath)) {
    logger.error("FTP directory switch failed");
    return false;
   }
   // upload files
   for (File localFile : localFiles) {
    logger.info("FTP upload path:{},file={}", uploadPath, localFile.toString());

    in = new FileInputStream(localFile);
    ByteArrayOutputStream resout = new ByteArrayOutputStream();
    int read = -1;
    byte[] indata = new byte[BYTE_SIZE];
    while ((read = in.read(indata)) != -1) {
     resout.write(indata, 0, read);
    }

    byteIn = new ByteArrayInputStream(resout.toByteArray());
    ftpClient.storeFile(localFile.getName(), byteIn);

    if (in != null) {
     in.close();
    }

    if (byteIn != null) {
     byteIn.close();
    }
   }

   ftpClient.logout();

   return true;
  } catch (Exception e) {
   logger.error("error:", e);
  } finally {
   if (in != null) {
    try {
     in.close();
    } catch (Exception e) {
     logger.error("FileInputStream failed to close:", e);
    }
   }

   if (byteIn != null) {
    try {
     byteIn.close();
    } catch (Exception e) {
     logger.error("FileInputStream failed to close:", e);
    }
   }

   if (ftpClient != null && ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException e) {
     logger.error("FTP connection failed to close:", e);
    }

   }
  }

  return false;
 }

 /**
  * Determine if a file exists
  * @param ftpFileName
  * @return
  */
 public boolean ifFilePresent(String ftpFileName) {

  boolean exist = false;
  FTPClient ftpClient = null;
  InputStream in = null;

  try {
   ftpClient = connectFTPClient();
   if (ftpClient == null) {
    return false;
   }

   if (!ftpClient.changeWorkingDirectory(downloadPath)) {
    logger.error("FTP directory switch failed");
    return false;
   }

   logger.info("FTP download path{},file{}", downloadPath, ftpFileName);
   // Determine if the file exists on the FTP
   in = ftpClient.retrieveFileStream(ftpFileName);
   if (in == null || ftpClient.getReplyCode() == FTPReply.FILE_UNAVAILABLE) {
    logger.error("File on FTP server" + downloadPath + ftpFileName + "Does not exist!");
    return false;
   }

   ftpClient.completePendingCommand();
   exist = true;

  } catch (Exception e) {
   logger.error("Judging whether there is an error in the file on FTP:", e);
  } finally {
   if (in != null) {
    try {
     in.close();
    } catch (IOException e) {
     logger.error("FileInputStream failed to close:", e);
    }
   }

   if (ftpClient != null && ftpClient.isConnected()) {
    try {
     ftpClient.disconnect();
    } catch (IOException e) {
     logger.error("FTP connection failed to close:", e);
    }
   }
  }

  return exist;
 }

 public String getHost() {
  return host;
 }

 public void setHost(String host) {
  this.host = host;
 }

 public int getPort() {
  return port;
 }

 public void setPort(int port) {
  this.port = port;
 }

 public String getUserName() {
  return userName;
 }

 public void setUserName(String userName) {
  this.userName = userName;
 }

 public String getPassword() {
  return password;
 }

 public void setPassword(String password) {
  this.password = password;
 }

 public String getDownloadPath() {
  return downloadPath;
 }

 public void setDownloadPath(String downloadPath) {
  this.downloadPath = downloadPath;
 }

 public String getUploadPath() {
  return uploadPath;
 }

 public void setUploadPath(String uploadPath) {
  this.uploadPath = uploadPath;
 }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325192543&siteId=291194637