链接ftp代码

package com.yqjr.nbs.car.af.ln.web.rest;

import com.xxljob.jobhandler.FTPAutoDownloadInvoiceTask;
import com.xxljob.jobhandler.FTPAutoUploadInvoiceTask;
import com.yqjr.nbs.car.af.ln.constant.ConstEnum;
import com.yqjr.nbs.common.dto.ResultDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * @version 1.0.0
 * @项目名称: car-af-ln-core模块
 * @类名称: FpExtraInfoValueResource
 * @类描述: #资源类
 * @功能描述:
 * @创建人: lwj
 * @创建时间: 2019-8-28 15:53:35
 * @修改备注:
 * @修改记录: 修改时间    修改人员    修改原因
 * -------------------------------------------------------------
 * @Copyright (c) 一汽金融-版权所有
 */


@RestController
@RequestMapping("/api/ftpInvoiceTask")
public class FTPInvoiceTask {

    @Autowired
    private FTPAutoUploadInvoiceTask ftpAutoUploadInvoiceTask;

    @Autowired
    private FTPAutoDownloadInvoiceTask ftpAutoDownloadInvoiceTask;

    /**
     * ftp电子发票上传
     * @author lwj
     */
    @GetMapping("/autoUploadInvoice")
    public ResultDto autoUploadInvoice() {
        ResultDto res = new ResultDto();
        try {
            ftpAutoUploadInvoiceTask.autoUploadInvoice();
        }catch (Exception e){
            res.setCode(ConstEnum.FAIL_0000.getCode());
            res.setMessage(e.getMessage());
           return  res;
        }
        res.setCode(ResultDto.SUCCESS_CODE);
        res.setMessage(ResultDto.SUCCESS_MESSAGE);
        return res;
    }

    /**
     * ftp电子发票下载
     * @author lwj
     */
    @GetMapping("/autoDownloadInvoice")
    public ResultDto autoDownloadInvoice() {
        ResultDto res = new ResultDto();
        try {
            ftpAutoDownloadInvoiceTask.autoDownloadInvoice();
        }catch (Exception e){
            res.setCode(ConstEnum.FAIL_0000.getCode());
            res.setMessage(e.getMessage());
            return  res;
        }
        res.setCode(ResultDto.SUCCESS_CODE);
        res.setMessage(ResultDto.SUCCESS_MESSAGE);
        return res;
    }

}

package com.xxljob.jobhandler;

import cn.com.yusys.yusp.commons.job.core.biz.model.ReturnT;
import cn.com.yusys.yusp.commons.job.core.handler.IJobHandler;
import cn.com.yusys.yusp.commons.job.core.handler.annotation.JobHandler;
import com.yqjr.nbs.car.af.ln.constant.ConstEnum;
import com.yqjr.nbs.car.af.ln.domain.PushInvoiceLog;
import com.yqjr.nbs.car.af.ln.dto.InvoiceInfoDto;
import com.yqjr.nbs.car.af.ln.infa.DealerService;
import com.yqjr.nbs.car.af.ln.repository.mapper.CcClientCorpMapper;
import com.yqjr.nbs.car.af.ln.repository.mapper.PushInvoiceLogMapper;
import com.yqjr.nbs.car.af.ln.util.FTPConfig;
import com.yqjr.nbs.car.af.ln.util.GenericCalendar;
import com.yqjr.nbs.car.af.ln.util.WriterAndReadUtil;
import com.yqjr.nbs.car.af.mkmm.dto.dlrextsetting.DealerInvoiceDto;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 一汽金融消息平台
 *
 * @author lwj ftp电子发票上传
 */

@JobHandler(value = "FTPAutoUploadInvoice")
@Service
public class FTPAutoUploadInvoiceTask extends IJobHandler {

    @Autowired
    private CcClientCorpMapper ccClientCorpMapper;

    @Autowired
    private PushInvoiceLogMapper pushInvoiceLogMapper;

    @Autowired
    private DealerService dealerService;

    @Autowired
    private FTPConfig ftpUtils;

    private Logger logger = LoggerFactory.getLogger(FTPAutoUploadInvoiceTask.class);

    /*生产环境:10.9.237.153 /home/oracle/tax/af/in/YYYYMM/
    测试环境:10.9.237.146 /home/oracle/tax/af/in/YYYYMM*/

    //数据上传文件路径
    private String uploadUrl = "";

    //上传存储文件名称
    private String uploadTxtName = "";


    @Override
    public ReturnT execute(String s) throws Exception {
        logger.info("【金融-电子发票上传-自动任务开始】");
        autoUploadInvoice();
        logger.info("【金融-电子发票上传-自动任务结束】");
        return ReturnT.SUCCESS;
    }


    /**
     * 每月1号零点定时获取开具电子发票数据生成txt文件并实现文件上传
     *
     * @throws Exception
     */
    public void autoUploadInvoice() throws Exception {
        String date = getDate();
        Long comtype = Long.parseLong(ConstEnum.COMTYPE.getCode());
        Long ptype = Long.parseLong(ConstEnum.PTYPE.getCode());
        boolean flag = false;
        //获取文件存储时间

        String faren = "AF";
        switch (comtype.intValue()) {
            case 2:
                faren = "FL";
                break;
            case 3:
                faren = "FAF";
                break;
            default:
                faren = "AF";
                break;
        }
        List dealerInvoiceDtos = dealerService.getDealerByInvoice();
        List ecifIds =  new ArrayList<>();
        for (DealerInvoiceDto dealerInvoiceDto :dealerInvoiceDtos ) {
            if (dealerInvoiceDto.getEcifId() != null) {
                ecifIds.add(dealerInvoiceDto.getEcifId());
            }
        }
        System.out.println(ecifIds);
        List invoiceList = ccClientCorpMapper.selectInvoice(ecifIds);

        String localPath = "/u02/oracle/invoice/" + faren + "/in/" + date + "/";
        String localFileName = faren.toUpperCase() + "_CSTM_IN_" + date + "_TAX.txt";
        String localFileUrl = localPath + localFileName;
        String localFileBak = "/u02/oracle/invoice/" + faren + "/in/bak/" + date + "/" + new GenericCalendar().getTimeInMillis() + "/" + localFileName;
        WriterAndReadUtil.write(invoiceList, localFileUrl, date);
        //文件上传到ftp服务器
        uploadUrl = "/home/oracle/tax/" + faren + "/in/";//+ date;
        // 初始化FTPClient
        ftpUtils.setFtpClient(new FTPClient());
        PushInvoiceLog pushInvoiceLog = new PushInvoiceLog();
        pushInvoiceLog.setDataSize(new Long(invoiceList.size()));
        pushInvoiceLog.setComptype(comtype.intValue());
        pushInvoiceLog.setPtype(ptype.intValue());
        pushInvoiceLog.setTransTime(date);
        pushInvoiceLog.setTxtName(localFileName);
        pushInvoiceLog.setPushType(1L);
        pushInvoiceLogMapper.insert(pushInvoiceLog);
        try {
            if (ftpUtils.ftpLogin()) {
                ftpUtils.uploadDirectory(localPath, uploadUrl);
                File file = new File(localFileUrl);
                copyFile(file, localFileBak);
                if (file.exists() || file.isDirectory()) {
                    file.delete();
                }
                flag = true;
                ftpUtils.ftpLogOut();
            }
            pushInvoiceLog.setSuccessFlag(1L);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            String stackTraceString = sw.getBuffer().toString();
            pw.close();
            pushInvoiceLog.setErrorInfo(stackTraceString);
            pushInvoiceLog.setSuccessFlag(0L);
        } finally {
            try {
                ftpUtils.ftpLogOut();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pushInvoiceLogMapper.updateByPrimaryKey(pushInvoiceLog);

    }

    /**
     * 获取当前月份前一个月的日期
     * return 此格式的日期 (yyyymm)
     *
     * @throws Exception
     */
    public String getDate() throws Exception {
        String date = "";
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(now);
        Long year = Long.parseLong(str.substring(0, 4));
        Long mon = Long.parseLong(str.substring(5, 7));
        if (mon > 12) {
            year++;
        } else {
            mon++;
        }
        if (mon < 10) {
            date = "" + year + "0" + mon;
        } else {
            date = "" + year + mon;
        }
        return date;
    }

    public void copyFile(File oldFile, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            if (oldFile.exists()) { //文件存在时
                File file = new File(newPath);
                File parent = file.getParentFile();
                if (parent == null || !parent.exists()) {
                    parent.mkdirs();
                }
                InputStream inStream = new FileInputStream(oldFile); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[2048];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();
        }
    }
}

package com.xxljob.jobhandler;

import cn.com.yusys.yusp.commons.job.core.biz.model.ReturnT;
import cn.com.yusys.yusp.commons.job.core.handler.IJobHandler;
import cn.com.yusys.yusp.commons.job.core.handler.annotation.JobHandler;
import com.yqjr.nbs.car.af.ln.constant.ConstEnum;
import com.yqjr.nbs.car.af.ln.domain.InvoiceInfo;
import com.yqjr.nbs.car.af.ln.domain.PushInvoiceLog;
import com.yqjr.nbs.car.af.ln.repository.mapper.InvoiceInfoMapper;
import com.yqjr.nbs.car.af.ln.repository.mapper.PushInvoiceLogMapper;
import com.yqjr.nbs.car.af.ln.util.FTPConfig;
import com.yqjr.nbs.car.af.ln.util.WriterAndReadUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * 一汽金融消息平台
 *
 * @author lwj ftp电子发票下载
 */

@JobHandler(value = "FTPAutoDownloadInvoice")
@Service
public class FTPAutoDownloadInvoiceTask extends IJobHandler {

    @Autowired
    private InvoiceInfoMapper invoiceInfoMapper;

    @Autowired
    private FTPConfig ftpUtils;

    @Autowired
    private PushInvoiceLogMapper pushInvoiceLogMapper;

    private Logger logger = LoggerFactory.getLogger(FTPAutoDownloadInvoiceTask.class);

    /*生产环境:10.9.237.153 /home/oracle/tax/af/in/YYYYMM/
    测试环境:10.9.237.146 /home/oracle/tax/af/in/YYYYMM*/

    //数据下载文件路径
    private String downloadUrl = "";

    //下载存储文件名称
    private String downloadTxtName = "";

    @Override
    public ReturnT execute(String s) throws Exception {
        logger.info("【金融-电子发票下载-自动任务开始】");
        autoDownloadInvoice();
        logger.info("【金融-电子发票下载-自动任务结束】");
        return ReturnT.SUCCESS;
    }


    /**
     * 每月4号零点定时下载开具电子发票数据并存入数据库
     *
     * @throws Exception
     */
    public void autoDownloadInvoice() throws Exception {
        String date = getDate();
        Long comtype = Long.parseLong(ConstEnum.COMTYPE.getCode());
        Long ptype = Long.parseLong(ConstEnum.PTYPE.getCode());
        String faren = "af";
        switch (comtype.intValue()) {
            case 2:
                faren = "fl";
                break;
            case 3:
                faren = "faf";
                break;
            default:
                faren = "af";
                break;
        }
        //从ftp服务器下载文件到指定文件路径
        downloadUrl = "/home/oracle/tax/" + faren.toUpperCase() + "/out/" + date;
        downloadTxtName = faren.toUpperCase() + "_CSTM_OUT_" + date + "_TAX.txt";
        PushInvoiceLog pushInvoiceLog = new PushInvoiceLog();
        pushInvoiceLog.setPushType(2L);
        pushInvoiceLog.setComptype(comtype.intValue());
        pushInvoiceLog.setPtype(ptype.intValue());
        pushInvoiceLog.setTransTime(date);
        pushInvoiceLog.setTxtName(downloadTxtName);
        pushInvoiceLogMapper.insert(pushInvoiceLog);
        try {
             // 初始化FTPClient
            ftpUtils.setFtpClient(new FTPClient());
            if (ftpUtils.ftpLogin()) {
                String localdir = "/u02/oracle/invoice/" + faren + "/out/";
                File file = new File(localdir + downloadTxtName);
                File parent = file.getParentFile();
                if (parent == null || !parent.exists()) {
                    parent.mkdirs();
                }
                boolean flag = ftpUtils.downloadFile(downloadTxtName, localdir, downloadUrl);
                //文件下载成功,读取指定文件中的内容并解析存入数据库
                if (flag) {
                    WriterAndReadUtil writerAndReadUtil = new WriterAndReadUtil();
                    List invoiceInfoList = writerAndReadUtil.read("/u02/oracle/invoice/" + faren + "/out/" + downloadTxtName);
                    pushInvoiceLog.setDataSize(new Long(invoiceInfoList.size()));
                    if (invoiceInfoList.size() <= 0) {
                        logger.info("下载文件中内容为空!!!");
                    } else {
                        //删除当前日期的数据
                        logger.info("记录数:" + invoiceInfoList.size());
                        invoiceInfoMapper.updateInvoiceByDate(date);
                        for (String info : invoiceInfoList) {
                            /**
                             * 保存
                             */
                            InvoiceInfo invoiceInfo = new InvoiceInfo();
                            /**info数据结构:纳税识别号@|@客户编号@|@YYYYMM@|@发票号码@|@发票代码@|@URL@|@downloadURL@|@品牌@|@+(4个备用字段,varchar2(100),不传)
                             * 测试数据结构:纳税识别号@|@客户编号@|@YYYYMM@|@客户邮箱
                             */
                            String[] content = info.split("@\\|@");
                            logger.info("" + content.length);
                            invoiceInfo.setBatchId(pushInvoiceLog.getId());
                            invoiceInfo.setIdentificatCode(content[0]);
                            invoiceInfo.setUserId(content[1]);
                            invoiceInfo.setInvoiceDate(content[2]);
                            invoiceInfo.setInvoiceNumber(content[3]);
                            invoiceInfo.setInvoiceCode(content[4]);
                            invoiceInfo.setInvoiceUrl(content[5]);
                            invoiceInfo.setInvoiceDownloadUrl(content[6]);
                            invoiceInfo.setBrandId(content[7]);
                            if (content.length == 9 && !" ".equals(content[8]) && content[8] != null) {
                                invoiceInfo.setNote1(content[8]);
                            }
                            if (content.length == 10 && !" ".equals(content[9]) && content[9] != null) {
                                invoiceInfo.setNote1(content[9]);
                            }
                            if (content.length == 11 && !" ".equals(content[10]) && content[10] != null) {
                                invoiceInfo.setNote1(content[10]);
                            }
                            if (content.length == 12 && !" ".equals(content[11]) && content[11] != null) {
                                invoiceInfo.setNote1(content[11]);
                            }
                            invoiceInfo.setComtype(comtype.toString());
                            invoiceInfo.setPtype(ptype.toString());
                            invoiceInfoMapper.insert(invoiceInfo);
                        }
                    }
                    pushInvoiceLog.setSuccessFlag(1L);
                    logger.info(faren + " " + date + "下载处理完成");
                } else {
                    throw new Exception("下载失败,从服务器上查看原因");
                }
                ftpUtils.ftpLogOut();
            }
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
            StringWriter sw = new StringWriter();
            PrintWriter pw = new PrintWriter(sw, true);
            e.printStackTrace(pw);
            String stackTraceString = sw.getBuffer().toString();
            pw.close();
            pushInvoiceLog.setErrorInfo(stackTraceString.length() > 0 ? stackTraceString : faren + " " + date + "下载失败");
            pushInvoiceLog.setSuccessFlag(0L);
            logger.info(faren + " " + date + "下载处理发生异常,需要从服务器日志上排查问题");
        } finally {
            try {
                ftpUtils.ftpLogOut();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pushInvoiceLogMapper.updateByPrimaryKey(pushInvoiceLog);
    }

    /**
     * 获取当前月份前一个月的日期
     * return 此格式的日期 (yyyymm)
     *
     * @throws Exception
     */
    public String getDate() throws Exception {
        String date = "";
        Date now = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String str = sdf.format(now);
        Long year = Long.parseLong(str.substring(0, 4));
        Long mon = Long.parseLong(str.substring(5, 7));
        if (mon > 12) {
            year++;
        } else {
            mon++;
        }
        if (mon < 10) {
            date = "" + year + "0" + mon;
        } else {
            date = "" + year + mon;
        }
        return date;
    }

    public void copyFile(File oldFile, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            if (oldFile.exists()) { //文件存在时
                File file = new File(newPath);
                File parent = file.getParentFile();
                if (parent == null || !parent.exists()) {
                    parent.mkdirs();
                }
                InputStream inStream = new FileInputStream(oldFile); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[2048];
                int length;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    logger.info("" + bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
                fs.close();
            }
        } catch (Exception e) {
            // TODO: handle exception
            logger.info("复制单个文件操作出错");
            e.printStackTrace();
        }
    }
}

package com.yqjr.nbs.car.af.ln.util;

import lombok.Data;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.TimeZone;

@Data
@Configuration
@ConfigurationProperties(prefix = "ftp")
public class FTPConfig {

    private Logger logger = LoggerFactory.getLogger(FTPConfig.class);

    // ftp服务器地址
//    @Value("${ftp.host}")
    private String host;
    // ftp服务器端口号默认为21
//    @Value("${ftp.port}")
    private int port;
    // ftp登录账号
//    @Value("${ftp.username}")
    private String username;
    // ftp登录密码
//    @Value("${ftp.password}")
    private String password;
//    @Value("${ftp.bufferSize}")
    private int bufferSize;
//    @Value("${ftp.encoding}")
    private String encoding;

    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 int getBufferSize() {
        return bufferSize;
    }

    public void setBufferSize(int bufferSize) {
        this.bufferSize = bufferSize;
    }

    public String getEncoding() {
        return encoding;
    }

    public void setEncoding(String encoding) {
        this.encoding = encoding;
    }

    public FTPClient getFtpClient() {
        return ftpClient;
    }

    public void setFtpClient(FTPClient ftpClient) {
        this.ftpClient = ftpClient;
    }

    private FTPClient ftpClient;

    public boolean ftpLogin() {
        boolean isLogin = false;
        FTPClientConfig ftpClientConfig = new FTPClientConfig();
        ftpClientConfig.setServerTimeZoneId(TimeZone.getDefault().getID());
        this.ftpClient.configure(ftpClientConfig);
        this.ftpClient.setControlEncoding(this.encoding);
        logger.debug(this.host);
        logger.debug("" + this.port);
        logger.debug(this.encoding);
        logger.debug(this.username);
        logger.debug(this.password);

        try {
            if (this.port > 0) {
                this.ftpClient.connect(this.host, this.port);
            } else {
                this.ftpClient.connect(this.host);
            }

            int reply = this.ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                this.ftpClient.disconnect();
                logger.error("登录FTP服务失败!");
                return isLogin;
            }

            this.ftpClient.login(this.username, this.password);
            this.ftpClient.enterLocalPassiveMode();
            this.ftpClient.setFileType(2);
            logger.info("恭喜" + this.username + "成功登陆FTP服务器");
            isLogin = true;
        } catch (Exception var4) {
            var4.printStackTrace();
            logger.error(this.username + "登录FTP服务失败!" + var4.getMessage());
        }

        this.ftpClient.setBufferSize(this.bufferSize);
        this.ftpClient.setDataTimeout(30000);
        return isLogin;
    }

    public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath) {
        File src = new File(localDirectory);

        try {
            remoteDirectoryPath = remoteDirectoryPath + src.getName() + "/";
            this.ftpClient.makeDirectory(remoteDirectoryPath);
        } catch (IOException var7) {
            var7.printStackTrace();
            logger.info(remoteDirectoryPath + "目录创建失败");
        }

        File[] allFile = src.listFiles();

        int currentFile;
        for (currentFile = 0; currentFile < allFile.length; ++currentFile) {
            if (!allFile[currentFile].isDirectory()) {
                String srcName = allFile[currentFile].getPath().toString();
                this.uploadFile(new File(srcName), remoteDirectoryPath);
            }
        }

        for (currentFile = 0; currentFile < allFile.length; ++currentFile) {
            if (allFile[currentFile].isDirectory()) {
                this.uploadDirectory(allFile[currentFile].getPath().toString(), remoteDirectoryPath);
            }
        }

        return true;
    }


    public boolean uploadFile(File localFile, String remoteUpLoadePath) {
        BufferedInputStream inStream = null;
        boolean success = false;

        boolean var7;
        try {
            this.ftpClient.changeWorkingDirectory(remoteUpLoadePath);
            inStream = new BufferedInputStream(new FileInputStream(localFile));
            logger.info(localFile.getName() + "开始上传.....");
            this.ftpClient.setBufferSize(this.bufferSize);
            success = this.ftpClient.storeFile(localFile.getName(), inStream);
            logger.info("success::" + success);
            if (!success) {
                return success;
            }

            logger.info(localFile.getName() + "上传成功");
            var7 = success;
        } catch (FileNotFoundException var18) {
            var18.printStackTrace();
            logger.error(localFile + "未找到");
            return success;
        } catch (IOException var19) {
            var19.printStackTrace();
            return success;
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }

        }

        return var7;
    }

    public void ftpLogOut() {
        if (this.ftpClient != null && this.ftpClient.isConnected()) {
            try {
                boolean reuslt = this.ftpClient.logout();
                if (reuslt) {
                    logger.info("成功退出服务器");
                }
            } catch (IOException var10) {
                var10.printStackTrace();
                logger.warn("退出FTP服务器异常!" + var10.getMessage());
            } finally {
                try {
                    this.ftpClient.disconnect();
                } catch (IOException var9) {
                    var9.printStackTrace();
                    logger.warn("关闭FTP服务器的连接异常!");
                }

            }
        }

    }

    public boolean downloadFile(String remoteFileName, String localDires, String remoteDownLoadPath) {
        String strFilePath = localDires + remoteFileName;
        BufferedOutputStream outStream = null;
        boolean success = false;

        try {
            this.ftpClient.changeWorkingDirectory(remoteDownLoadPath);
            outStream = new BufferedOutputStream(new FileOutputStream(strFilePath));
            logger.info(remoteFileName + "开始下载....");
            success = this.ftpClient.retrieveFile(remoteFileName, outStream);
            if (success) {
                logger.info(remoteFileName + "成功下载到" + strFilePath);
                boolean var9 = success;
                return var9;
            }
        } catch (Exception var18) {
            var18.printStackTrace();
            logger.error(remoteFileName + "下载失败");
        } finally {
            if (outStream != null) {
                try {
                    outStream.flush();
                    outStream.close();
                } catch (IOException var17) {
                    var17.printStackTrace();
                }
            }

        }

        if (!success) {
            logger.error(remoteFileName + "下载失败!!!");
        }

        return success;
    }
}

你可能感兴趣的:(链接ftp代码)