FTP

添加依赖:

<!--添加FTP依赖-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.3</version>
        </dependency>

从FTP协议中读取文件:

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;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ResourceBundle;


/**
*
*ftp.hostname=172.19.xx.xx
*ftp.port=21
*ftp.username=admin
*ftp.password=123456
*ftp.pathname=/
 *
 * 初始化FTP
 */
@Component
public class FTPClientRequest {
    //private static final Log logger = LogFactory.getLog(FTPClientRequest.class);
    private static final Logger logger = Logger.getLogger(Async2tda.class);
    private static ResourceBundle resource = ResourceBundle.getBundle("application");
    private static FTPClient ftpClient = null;

    @Autowired
    private Async2tda async2tda;
/**
 * 初始化FTP
 */
public FTPClient initFTP(){
    try {
        logger.debug("FTPClient 初始化");
        ftpClient = new FTPClient();
        ftpClient.setConnectTimeout(10000);
        ftpClient.setControlEncoding("GBK");
        ftpClient.setBufferSize(1024*1024);
        ftpClient.setControlKeepAliveTimeout(15000);
        ftpClient.setControlKeepAliveReplyTimeout(15000);
        String hostname = resource.getString("ftp1.hostname");
        Integer port = Integer.parseInt(resource.getString("ftp1.port"));
        String username = resource.getString("ftp1.username");
        String password = resource.getString("ftp1.password");
        String pathname = resource.getString("ftp1.pathname");
        if(!ftpClient.isConnected()){
            ftpClient.connect(hostname,port);
        }
        ftpClient.login(username,password);
        //跳转到文件目录
        ftpClient.changeWorkingDirectory(pathname);
        //设置连接模式,设置被动模式,在很多情况下由于防火墙等原因,主动模式不支持。
        ftpClient.enterLocalPassiveMode();
        if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
            logger.debug("FTP连接成功");
            return ftpClient;
        }else{
            ftpClient.disconnect();
            logger.debug("FTP连接失败");
        }
    } catch (Exception e) {
        logger.error("FTP连接异常:"+e);
    }
    return null;
}
     /**
     * 读取FTP的XML文件
     */
    public void readFilesFTP(){
        try {
            if (ftpClient == null || !FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                initFTP();
            }
            logger.debug("FTPClient 检测连接状态1");
            if (FTPReply.isPositiveCompletion(ftpClient.getReplyCode())){
                logger.debug("FTPClient 检测连接状态2");
                if (!ftpClient.isConnected()){
                    ftpClient.disconnect();
                    initFTP();
                }
                FTPFile[] ftpFiles = ftpClient.listFiles();
                logger.debug("ftpFiles 个数:"+ftpFiles.length);
                for (FTPFile ftpFile : ftpFiles) {
                    String fileName = ftpFile.getName();
                    //executorService.execute(new FileStreamRunable(fileName));
                    Future<String> future = executorService.submit(new FileStreamRunable(fileName));
                    future.get();
                    //async2tda.sendTdaXML(future.get());
                }
            }
        } catch (Exception e) {
            try {
                if (ftpClient != null) {
                    ftpClient.disconnect();
                }
            } catch (Exception e1) {
                logger.error("ftpClient close error:"+e1);
            }
            logger.error("readFilesFTP is error:"+e);
        }
    }

class FileStreamRunable implements Callable {
        private String fileName;
        public FileStreamRunable(String fileName){
            this.fileName = fileName;
        }

        @Override
        public String call() {
            String xmlStr = "";
            try {
                if (!StringUtils.isEmpty(fileName) && fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase().equals("xml")) {
                    InputStream inputStream = null;
                    BufferedInputStream input = null;
                    ByteArrayOutputStream outputStream  = null;
                    try {
                        try {
                            if (!ftpClient.isConnected()){
                                ftpClient.disconnect();
                                initFTP();
                            }
                            inputStream = ftpClient.retrieveFileStream(fileName);
                        } catch (Exception e) {
                            logger.error("retrieveFileStream error:"+e);
                        }
                        /*if (inputStream == null){
                            logger.debug("inputStream is null 进行初始化FTPClient");
                            ftpClient.disconnect();
                            ftpClient = null;
                            initFTP();
                            inputStream = ftpClient.retrieveFileStream(fileName);
                        }*/
                        if (inputStream != null) {
                            input = new BufferedInputStream(inputStream);
                            outputStream = new ByteArrayOutputStream();
                            byte[] buffer = new byte[1024];
                            int len = -1;
                            while ((len=input.read(buffer))!=-1){
                                outputStream.write(buffer,0,len);
                            }
                            xmlStr = new String( outputStream.toByteArray(),"GBK").replaceAll("
","");
                            ftpClient.deleteFile(fileName);
                            ftpClient.getReply();//循环读取文件流需要执行getReply,否则第二个文件流为null
                            logger.debug("读取FTP的XML原数据成功,并删除文件《"+fileName+"》");
                            async2tda.sendTdaXML(xmlStr);
                        }
                    } catch (IOException e) {
                        logger.error("读取文件错误:"+e);
                    } finally {
                        if (outputStream != null){
                            outputStream.close();
                        }
                        if (input != null){
                            input.close();
                        }
                        if (inputStream != null){
                            inputStream.close();
                        }
                        //ftpClient.completePendingCommand();//完成等待方法 ,如果一个连接中要连续读写多个文件,需要强行关流,在执行completePendingCommand 方法
                    }
                }
            } catch (IOException e) {
                logger.error("FileStreamRunable run error:"+e);
            }
            return xmlStr;
        }
    }
}
原文地址:https://www.cnblogs.com/lijianda/p/11857789.html