java实现通过FTP下载文件




import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.iflytek.dicom.config.GlobalConfig;

/**
 *
 * ClassName: FtpUtil
 * @Description: ftp工具类
 * @author wyl_0728
 * @date 2016年8月22日
 */
public class FtpUtil {

 private static Logger logger = LogManager.getLogger(FtpUtil.class.getName());
 
    private FTPClient ftp;
    private boolean is_connected;

    public FtpUtil() {
        ftp = new FTPClient();
        ftp.setControlEncoding("UTF-8");
        ftp.enterLocalPassiveMode();
        is_connected = false;
    }
    /*

*构造器 设置连接超时时间

*/
    public FtpUtil(int defaultTimeoutSecond, int connectTimeoutSecond, int dataTimeoutSecond){
        ftp = new FTPClient();
        is_connected = false;
        ftp.setControlEncoding("UTF-8");
        ftp.enterLocalPassiveMode();
        ftp.setDefaultTimeout(defaultTimeoutSecond * 1000);
        ftp.setConnectTimeout(connectTimeoutSecond * 1000);
        ftp.setDataTimeout(dataTimeoutSecond * 1000);
    }

    /**
     * Connects to FTP server.
     * host  port  username  password 通过配置文件读取
     */
    public FTPClient connect() throws IOException {
        // Connect to server.
        try {
         ftp.connect(GlobalConfig.getString("FTP_SERVER"),Integer.parseInt(GlobalConfig.getString("FTP_PORT")));
        } catch (UnknownHostException ex) {
            throw new IOException("Can't find FTP server '" + GlobalConfig.getString("FTP_SERVER") + "'");
        }

        // Check rsponse after connection attempt.
        int reply = ftp.getReplyCode();
        logger.info("------login -reply ="+reply); 
        if (!FTPReply.isPositiveCompletion(reply)) {
         logger.debug("---------------------##############################");
            disconnect();
            throw new IOException("Can't connect to server '" + GlobalConfig.getString("FTP_SERVER") + "'");
        }
        // Login.
        boolean flag =ftp.login(GlobalConfig.getString("FTP_USER"), GlobalConfig.getString("FTP_PWD"));
        logger.debug("------login -flag ="+flag);
        if (!flag) {
            is_connected = false;
            disconnect();
            throw new IOException("Can't login to server '" + GlobalConfig.getString("FTP_SERVER") + "'");
        } else {
            is_connected = true;
        }

        // Set data transfer mode.
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        logger.debug("------login -is_connected ="+is_connected);    
       return ftp;
    }

    /**

    * 上传实现
     * Uploads the file to the FTP server.
     *
     * @param ftpFileName
     *            server file name (with absolute path)
     * @param localFile
     *            local file to upload
     * @throws IOException
     *             on I/O errors
     */
    public void upload(String ftpFileName, File localFile) throws IOException {
        // File check.
        if (!localFile.exists()) {
            throw new IOException("Can't upload '" + localFile.getAbsolutePath() + "'. This file doesn't exist.");
        }

        // Upload.
        InputStream in = null;
        try {

            // Use passive mode to pass firewalls.
            ftp.enterLocalPassiveMode();

            in = new BufferedInputStream(new FileInputStream(localFile));
            if (!ftp.storeFile(ftpFileName, in)) {
                throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
            }

        } finally {
            try {
                in.close();
            } catch (IOException ex) {
            }
        }
    }

    /**
     * Downloads the file from the FTP server.
     * 下载实现
     * @param ftpFileName
     *            server file name (with absolute path)
     * @param localFile
     *            local file to download into
     * @throws IOException
     *             on I/O errors
     */
    public void download(String ftpFileName, File localFile) throws IOException {
        // Download.
        OutputStream out = null;
        try {
            // Use passive mode to pass firewalls.
            ftp.enterLocalPassiveMode();

            // Get file info.
            FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
            if (fileInfoArray == null) {
                throw new FileNotFoundException("File " + ftpFileName + " was not found on FTP server.");
            }

            // Check file size.
            FTPFile fileInfo = fileInfoArray[0];
            long size = fileInfo.getSize();
            if (size > Integer.MAX_VALUE) {
                throw new IOException("File " + ftpFileName + " is too large.");
            }

            // Download file.
            out = new BufferedOutputStream(new FileOutputStream(localFile));
            if (!ftp.retrieveFile(ftpFileName, out)) {
                throw new IOException("Error loading file " + ftpFileName + " from FTP server. Check FTP permissions and path.");
            }

            out.flush();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                }
            }
        }
    }

    /**
     * Removes the file from the FTP server.
     *
     * @param ftpFileName
     *            server file name (with absolute path)
     * @throws IOException
     *             on I/O errors
     */
    public void remove(String ftpFileName) throws IOException {
        if (!ftp.deleteFile(ftpFileName)) {
            throw new IOException("Can't remove file '" + ftpFileName + "' from FTP server.");
        }
    }

    /**
     * Lists the files in the given FTP directory.
     *
     * @param filePath
     *            absolute path on the server
     * @return files relative names list
     * @throws IOException
     *             on I/O errors
     */
    public List list(String filePath) throws IOException {
        List fileList = new ArrayList();
       
        // Use passive mode to pass firewalls.
        ftp.enterLocalPassiveMode();
       
        FTPFile[] ftpFiles = ftp.listFiles(filePath);
        int size = (ftpFiles == null) ? 0 : ftpFiles.length;
        for (int i = 0; i < size; i++) {
            FTPFile ftpFile = ftpFiles[i];
            if (ftpFile.isFile()) {
                fileList.add(ftpFile.getName());
            }
        }
       
        return fileList;
    }

    /**
     * Sends an FTP Server site specific command
     *
     * @param args
     *            site command arguments
     * @throws IOException
     *             on I/O errors
     */
    public void sendSiteCommand(String args) throws IOException {
        if (ftp.isConnected()) {
            try {
                ftp.sendSiteCommand(args);
            } catch (IOException ex) {
            }
        }
    }

    /**
     * Disconnects from the FTP server
     *
     * @throws IOException
     *             on I/O errors
     */
    public void disconnect() throws IOException {

        if (ftp.isConnected()) {
            try {
                ftp.logout();
                ftp.disconnect();
                is_connected = false;
            } catch (IOException ex) {
            }
        }
    }

    /**
     * Makes the full name of the file on the FTP server by joining its path and
     * the local file name.
     *
     * @param ftpPath
     *            file path on the server
     * @param localFile
     *            local file
     * @return full name of the file on the FTP server
     */
    public String makeFTPFileName(String ftpPath, File localFile) {
        if (ftpPath == "") {
            return localFile.getName();
        } else {
            String path = ftpPath.trim();
            if (path.charAt(path.length() - 1) != '/') {
                path = path + "/";
            }

            return path + localFile.getName();
        }
    }

    /**
     * Test coonection to ftp server
     *
     * @return true, if connected
     */
    public boolean isConnected() {
        return is_connected;
    }

    /**
     * Get current directory on ftp server
     *
     * @return current directory
     */
    public String getWorkingDirectory() {
        if (!is_connected) {
            return "";
        }

        try {
            return ftp.printWorkingDirectory();
        } catch (IOException e) {
        }

        return "";
    }

    /**
     * Set working directory on ftp server
     *
     * @param dir
     *            new working directory
     * @return true, if working directory changed
     */
    public boolean setWorkingDirectory(String dir) {
        if (!is_connected) {
            return false;
        }

        try {
            return ftp.changeWorkingDirectory(dir);
        } catch (IOException e) {
        }

        return false;
    }

    /**
     * Change working directory on ftp server to parent directory
     *
     * @return true, if working directory changed
     */
    public boolean setParentDirectory() {
        if (!is_connected) {
            return false;
        }

        try {
            return ftp.changeToParentDirectory();
        } catch (IOException e) {
        }

        return false;
    }

    /**
     * Get parent directory name on ftp server
     *
     * @return parent directory
     */
    public String getParentDirectory() {
        if (!is_connected) {
            return "";
        }

        String w = getWorkingDirectory();
        setParentDirectory();
        String p = getWorkingDirectory();
        setWorkingDirectory(w);

        return p;
    }

    /**
     * Get directory contents on ftp server
     *
     * @param filePath
     *            directory
     * @return list of FTPFileInfo structures
     * @throws IOException
    
    public List listFiles(String filePath) throws IOException {
        List fileList = new ArrayList();
       
        // Use passive mode to pass firewalls.
        ftp.enterLocalPassiveMode();
        FTPFile[] ftpFiles = ftp.listFiles(filePath);
        int size = (ftpFiles == null) ? 0 : ftpFiles.length;
        for (int i = 0; i < size; i++) {
            FTPFile ftpFile = ftpFiles[i];
            FfpFileInfo fi = new FfpFileInfo();
            fi.setName(ftpFile.getName());
            fi.setSize(ftpFile.getSize());
            fi.setTimestamp(ftpFile.getTimestamp());
            fi.setType(ftpFile.isDirectory());
            fileList.add(fi);
        }

        return fileList;
    }
*/
    /**
     * Get file from ftp server into given output stream
     *
     * @param ftpFileName
     *            file name on ftp server
     * @param out
     *            OutputStream
     * @throws IOException
     */
    public void getFile(String ftpFileName, OutputStream out) throws IOException {
        try {
            // Use passive mode to pass firewalls.
            ftp.enterLocalPassiveMode();
           
            // Get file info.
            FTPFile[] fileInfoArray = ftp.listFiles(ftpFileName);
            if (fileInfoArray == null) {
                throw new FileNotFoundException("File '" + ftpFileName + "' was not found on FTP server.");
            }

            // Check file size.
            FTPFile fileInfo = fileInfoArray[0];
            long size = fileInfo.getSize();
            if (size > Integer.MAX_VALUE) {
                throw new IOException("File '" + ftpFileName + "' is too large.");
            }

            // Download file.
            if (!ftp.retrieveFile(ftpFileName, out)) {
                throw new IOException("Error loading file '" + ftpFileName + "' from FTP server. Check FTP permissions and path.");
            }

            out.flush();

        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                }
            }
        }
    }

    /**
     * Put file on ftp server from given input stream
     *
     * @param ftpFileName
     *            file name on ftp server
     * @param in
     *            InputStream
     * @throws IOException
     */
    public void putFile(String ftpFileName, InputStream in) throws IOException {
        try {
            // Use passive mode to pass firewalls.
            ftp.enterLocalPassiveMode();
           
            if (!ftp.storeFile(ftpFileName, in)) {
                throw new IOException("Can't upload file '" + ftpFileName + "' to FTP server. Check FTP permissions and path.");
            }
        } finally {
            try {
                in.close();
            } catch (IOException ex) {
            }
        }
    }

    public boolean downloadFile(String ftpFileName, File localFile){
  if(localFile.exists()){
   return true;
  }
  boolean flag = false;
  // Download.
  OutputStream out = null;
  try {
   // Use passive mode to pass firewalls.
   ftp.enterLocalPassiveMode();
   // Download file.
   out = new BufferedOutputStream(new FileOutputStream(localFile));
   if (!ftp.retrieveFile(ftpFileName, out)) {
    throw new IOException("Error loading file " + ftpFileName
      + " from FTP server. Check FTP permissions and path.");
   }
   out.flush();
   out.close();
   flag = true;
  } catch (Exception e) {
   logger.info(e.getMessage());
  } finally {
   if (out != null) {
    try {
     out.close();
    } catch (IOException ex) {
    }
   }
  }
  return flag;
 }
}


*************************************************************************
import java.lang.reflect.Method;
import java.util.Properties;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;
import org.springframework.context.ApplicationContext;
import org.springframework.core.io.support.PropertiesLoaderSupport;

/**
 * {读取配置信息的类}
 *
 * @author CYF
 * @created 2014-9-23 下午2:34:15
 * @lastModified
 * @history
 */
public class GlobalConfig {
 private static Logger logger = LogManager.getLogger(GlobalConfig.class.getName());
    private static Properties properties = new Properties();

    static {
        // 初始化,配置属性到本地properties中
        try {
            // 读取applicationCotext对象
            ApplicationContext applicationContext = SpringContextUtils
                    .getApplicationContext();
            // get the names of BeanFactoryPostProcessor
            String[] postProcessorNames = applicationContext
                    .getBeanNamesForType(BeanFactoryPostProcessor.class, true,
                            true);

            for (String ppName : postProcessorNames) {
                // get the specified BeanFactoryPostProcessor
                BeanFactoryPostProcessor beanProcessor = applicationContext
                        .getBean(ppName, BeanFactoryPostProcessor.class);
                // check whether the beanFactoryPostProcessor is
                // instance of the PropertyResourceConfigurer
                // if it is yes then do the process otherwise continue
                if (beanProcessor instanceof PropertyResourceConfigurer) {
                    PropertyResourceConfigurer propertyResourceConfigurer = (PropertyResourceConfigurer) beanProcessor;

                    // get the method mergeProperties
                    // in class PropertiesLoaderSupport
                    Method mergeProperties = PropertiesLoaderSupport.class
                            .getDeclaredMethod("mergeProperties");
                    // get the props
                    mergeProperties.setAccessible(true);
                    Properties props = (Properties) mergeProperties
                            .invoke(propertyResourceConfigurer);

                    // get the method convertProperties
                    // in class PropertyResourceConfigurer
                    Method convertProperties = PropertyResourceConfigurer.class
                            .getDeclaredMethod("convertProperties",
                                    Properties.class);
                    // convert properties
                    convertProperties.setAccessible(true);
                    convertProperties.invoke(propertyResourceConfigurer, props);

                    properties.putAll(props);
                }
            }
        } catch (Exception e) {
            // 初始化属性读取失败
            logger.error("初始化属性读取失败", e);
        }
    }

    public static String getString(String key) {
        return properties.getProperty(key);
    }

    public static String getString(String key, String defaultValue) {
        return properties.getProperty(key, defaultValue);
    }

}

******************************************************************

public class TestFTP{

 private FtpUtil ftp = null;

 private FTPClient ftpClient = null;

public void batchDownloadFileByFtp(String imgUrl) {

 // 1.2 初始化FTP配置
  // 1.2.1 建立ftp连接
  ftp = new FtpUtil(500, 500, 500);
  ftpClient = ftp.connect();
  imgUrl =imgUrl.replace(PREFIX, "");
  // 创建文件夹
  String localFile = GlobalConfig.getString("pacsUrl")
    + String.valueOf(rsId)+"/"+fseriesNo;
  File file = new File(localFile);
  if (!file.exists() && !file.isDirectory()) {
   file.mkdirs();
  }
  // 1.3 循环下载文件
  // 转移到FTP服务器目录
  try {
   ftpClient.changeWorkingDirectory(imgUrl);
   FTPFile[] fs = ftpClient.listFiles();
   if (fs == null || fs.length == 0) {
    return;
   }
   for (FTPFile ftpFile : fs) {
    String fileName = ftpFile.getName();
    if(fileName.length()>10){
     if (new File(localFile + "/" + fileName).exists()) {
      new File(localFile + "/" + fileName).delete();
     }
     boolean flag = ftp.downloadFile(fileName, new File(localFile
       + "/" + fileName));
     // 下载成功
     if (flag) {
         //TODO 下载成功
     } else {
     //TODO下载失败
     }
    }else {
     continue;
    }
    
   }
  } catch (IOException e) {
   logger.info(e.getMessage());
  }
 }

}

你可能感兴趣的:(java,ftp)