经过最近多次调试,实际测试. 改用common.net插件进行远程备份,消除大文件备份中断问题
3个文件已修改
2个文件已添加
932 ■■■■■ 已修改文件
pom.xml 8 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/dto/FTPClientUtil.java 59 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/dto/FtpHelper.java 602 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/service/FtpService.java 168 ●●●● 补丁 | 查看 | 原始文档 | blame | 历史
src/main/java/com/whyc/service/FtpService2.java 95 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
pom.xml
@@ -192,13 +192,19 @@
            <systemPath>${pom.basedir}/src/main/resources/lib/jacob.jar</systemPath>
        </dependency>
        <dependency>
        <!--<dependency>
            <groupId>com.enterprisedt</groupId>
            <artifactId>edtFTPj</artifactId>
            <version>2.5.0</version>
            <scope>system</scope>
            <systemPath>${pom.basedir}/src/main/resources/lib/edtftpj.jar</systemPath>
        </dependency>-->
        <dependency>
            <groupId>commons-net</groupId>
            <artifactId>commons-net</artifactId>
            <version>3.6</version>
        </dependency>
        <dependency>
            <groupId>com.enterprisedt</groupId>
            <artifactId>edtFTPj-libs</artifactId>
src/main/java/com/whyc/dto/FTPClientUtil.java
New file
@@ -0,0 +1,59 @@
package com.whyc.dto;
import com.whyc.constant.YamlProperties;
import org.apache.commons.net.ftp.FTPClient;
import org.springframework.stereotype.Component;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@Component
public class FTPClientUtil {
    public static FTPClient connect(){
        FTPClient ftpClient = new FTPClient();
        try {
            ftpClient.connect(YamlProperties.ftpIp,YamlProperties.ftpPort);
            ftpClient.login(YamlProperties.ftpUserName,YamlProperties.ftpPassword);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
            final int bufferSize = 1024 * 1024;
            ftpClient.setBufferSize(bufferSize);
            return ftpClient;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static void transferFile(File originalFile, String descFilePath){
        FTPClient ftpClient = connect();
        if(ftpClient !=null) {
            FileInputStream fileInputStream = null;
            try {
                fileInputStream = new FileInputStream(originalFile);
                ftpClient.storeFile(descFilePath, fileInputStream);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    fileInputStream.close();
                    if (ftpClient.isConnected()) {
                        ftpClient.logout();
                        ftpClient.disconnect();
                    }
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }
}
src/main/java/com/whyc/dto/FtpHelper.java
@@ -1,301 +1,301 @@
package com.whyc.dto;
import com.enterprisedt.net.ftp.*;
import org.apache.commons.lang.StringUtils;
import java.io.*;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
public class FtpHelper {
    private FTPClient ftp;
    /**
     * 初始化Ftp信息
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
                     String ftpPassword) {
        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
    }
    /**
     * 连接到ftp
     *
     * @param ftpServer   ftp服务器地址
     * @param ftpPort     Ftp端口号
     * @param ftpUsername ftp 用户名
     * @param ftpPassword ftp 密码
     */
    public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
        ftp = new FTPClient();
        try {
            ftp.setControlEncoding("GBK");
            ftp.setRemoteHost(ftpServer);
            ftp.setRemotePort(ftpPort);
            ftp.setTimeout(1000*60*60*12);
            ftp.setConnectMode(FTPConnectMode.ACTIVE);
            ftp.connect();
            ftp.login(ftpUsername, ftpPassword);
            ftp.setType(FTPTransferType.BINARY);
        } catch (Exception e) {
            e.printStackTrace();
            ftp = null;
        }
    }
    /**
     * 更改ftp路径
     *
     * @param ftp
     * @param dirName
     * @return
     */
    public boolean checkDirectory(FTPClient ftp, String dirName) {
        boolean flag;
        try {
            ftp.chdir(dirName);
            flag = true;
        } catch (Exception e) {
            //e.printStackTrace();
            flag = false;
        }
        return flag;
    }
    /**
     * 断开ftp链接
     */
    public void disconnect() {
        try {
            if (ftp.connected()) {
                ftp.quit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 读取ftp文件流
     *
     * @param filePath ftp文件路径
     * @return s
     * @throws Exception
     */
    public InputStream downloadFile(String filePath) throws Exception {
        InputStream inputStream = null;
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                ftp.chdir(s);
            }
        }
        byte[] data;
        try {
            data = ftp.get(fileName);
            inputStream = new ByteArrayInputStream(data);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return inputStream;
    }
    /**
     * 上传文件到ftp
     *
     * @param file     文件对象
     * @param filePath 上传的路径
     * @throws Exception
     */
    public void uploadFile(File file, String filePath) throws Exception {
        InputStream inStream = new FileInputStream(file);
        uploadFile(inStream, filePath);
    }
    /**
     * 上传文件到ftp
     *
     * @param inStream 上传的文件流
     * @param filePath 上传路径
     * @throws Exception
     */
    public void uploadFile(InputStream inStream, String filePath)
            throws Exception {
        if (inStream == null) {
            return;
        }
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                s.trim();
                if (!checkDirectory(ftp, s)) {
                    if(!ftp.existsDirectory(s)) {
                        ftp.mkdir(s);
                    }
                    changeDirectory(s);
                }
            }
        }
        ftp.put(inStream, fileName);
        changeDirectory("/");
    }
    public void uploadFile2(File inFile,String fileName) throws IOException, FTPException {
        InputStream inStream = new FileInputStream(inFile);
        ftp.put(inStream, fileName);
    }
    /**
     * 删除ftp文件
     *
     * @param filePath 文件路径
     * @throws Exception
     */
    public void deleteFile(String filePath) throws Exception {
        String fileName = "";
        filePath = StringUtils.removeStart(filePath, "/");
        int len = filePath.lastIndexOf("/");
        if (len == -1) {
            if (filePath.length() > 0) {
                fileName = filePath;
            } else {
                throw new Exception("没有输入文件路径");
            }
        } else {
            fileName = filePath.substring(len + 1);
            String type = filePath.substring(0, len);
            String[] typeArray = type.split("/");
            for (String s : typeArray) {
                if (checkDirectory(ftp, s)) {
                    ftp.chdir(s);
                }
            }
        }
        ftp.delete(fileName);
    }
     //切换目录
    public void changeDirectory(String path) {
        if (!StringUtils.isEmpty(path)) {
            try {
                ftp.chdir(path);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    //读取文件列表
    public List<File> getFileList(String path) {
        List<File> rsList = new ArrayList<>();
        if (path == null || path.equals("")) {
            return rsList;
        }
        File file = new File(path);
        if (!file.exists()) {
            return rsList;
        }
        // 处理文件
        if (file.isFile()) {
            rsList.add(file);
            return rsList;
        }
        // 处理文件夹
        if (null == file.listFiles()) {
            rsList.add(file);
            return rsList;
        }
        LinkedList<File> forDealList = new LinkedList<>();
        forDealList.addAll(Arrays.asList(file.listFiles()));
        while (!forDealList.isEmpty()) {
            File firstFile = forDealList.removeFirst();
            // 处理文件
            if (firstFile.isFile()) {
                // 把文件自身先加入结果
                rsList.add(firstFile);
                continue;
            }
            // 处理文件夹
            File[] files = firstFile.listFiles();
            if (files == null) {
                continue;
            }
            for (File curr : files) {
                if (curr.isDirectory()) {
                    // 将此文件夹放入待处理列表
                    forDealList.add(curr);
                } else {
                    rsList.add(curr);
                }
            }
        }
        return rsList;
    }
    public void deleteDir(String dirName) throws IOException, FTPException, ParseException {
        FTPClient client = ftp;
        //String[] dir = client.dir(dirName, true);
        FTPFile[] ftpFiles = client.dirDetails(dirName);
        for (FTPFile ftpFile : ftpFiles) {
            if(ftpFile.isDir()){
                deleteDir(dirName+"/"+ftpFile.getName());
            }else{
                client.delete(dirName+"/"+ftpFile.getName());
            }
        }
        /*for (String subDirName : dir) {
            String name = subDirName.substring(subDirName.lastIndexOf(" ") + 1);
            if(subDirName.contains("<DIR>")){ //文件夹
                //name = new String(name.getBytes(StandardCharsets.ISO_8859_1),"GBK");
                deleteDir(dirName+"/"+name);
                //client.rmdir(dirName+"/"+name);
            }else{
                //name = new String(name.getBytes(StandardCharsets.ISO_8859_1),"GBK");
                client.delete(dirName+"/"+name);
            }
        }*/
        client.rmdir(dirName);
    }
    public String[] getDirList() throws IOException, FTPException {
        return ftp.dir();
    }
    public void mkdir(String dirPath) throws IOException, FTPException {
        ftp.mkdir(dirPath);
    }
}
//package com.whyc.dto;
//
//import com.enterprisedt.net.ftp.*;
//import org.apache.commons.lang.StringUtils;
//
//import java.io.*;
//import java.text.ParseException;
//import java.util.ArrayList;
//import java.util.Arrays;
//import java.util.LinkedList;
//import java.util.List;
//
//public class FtpHelper {
//    private FTPClient ftp;
//
//    /**
//     * 初始化Ftp信息
//     *
//     * @param ftpServer   ftp服务器地址
//     * @param ftpPort     Ftp端口号
//     * @param ftpUsername ftp 用户名
//     * @param ftpPassword ftp 密码
//     */
//    public FtpHelper(String ftpServer, int ftpPort, String ftpUsername,
//                     String ftpPassword) {
//        connect(ftpServer, ftpPort, ftpUsername, ftpPassword);
//    }
//
//    /**
//     * 连接到ftp
//     *
//     * @param ftpServer   ftp服务器地址
//     * @param ftpPort     Ftp端口号
//     * @param ftpUsername ftp 用户名
//     * @param ftpPassword ftp 密码
//     */
//    public void connect(String ftpServer, int ftpPort, String ftpUsername, String ftpPassword) {
//        ftp = new FTPClient();
//        try {
//            ftp.setControlEncoding("GBK");
//            ftp.setRemoteHost(ftpServer);
//            ftp.setRemotePort(ftpPort);
//            ftp.setTimeout(1000*60*60*12);
//            ftp.setConnectMode(FTPConnectMode.ACTIVE);
//            ftp.connect();
//            ftp.login(ftpUsername, ftpPassword);
//            ftp.setType(FTPTransferType.BINARY);
//        } catch (Exception e) {
//            e.printStackTrace();
//            ftp = null;
//        }
//    }
//
//    /**
//     * 更改ftp路径
//     *
//     * @param ftp
//     * @param dirName
//     * @return
//     */
//    public boolean checkDirectory(FTPClient ftp, String dirName) {
//        boolean flag;
//        try {
//            ftp.chdir(dirName);
//            flag = true;
//        } catch (Exception e) {
//            //e.printStackTrace();
//            flag = false;
//        }
//        return flag;
//    }
//
//    /**
//     * 断开ftp链接
//     */
//    public void disconnect() {
//        try {
//            if (ftp.connected()) {
//                ftp.quit();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    /**
//     * 读取ftp文件流
//     *
//     * @param filePath ftp文件路径
//     * @return s
//     * @throws Exception
//     */
//    public InputStream downloadFile(String filePath) throws Exception {
//        InputStream inputStream = null;
//        String fileName = "";
//        filePath = StringUtils.removeStart(filePath, "/");
//        int len = filePath.lastIndexOf("/");
//        if (len == -1) {
//            if (filePath.length() > 0) {
//                fileName = filePath;
//            } else {
//                throw new Exception("没有输入文件路径");
//            }
//        } else {
//            fileName = filePath.substring(len + 1);
//
//            String type = filePath.substring(0, len);
//            String[] typeArray = type.split("/");
//            for (String s : typeArray) {
//                ftp.chdir(s);
//            }
//        }
//        byte[] data;
//        try {
//            data = ftp.get(fileName);
//            inputStream = new ByteArrayInputStream(data);
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return inputStream;
//    }
//
//    /**
//     * 上传文件到ftp
//     *
//     * @param file     文件对象
//     * @param filePath 上传的路径
//     * @throws Exception
//     */
//    public void uploadFile(File file, String filePath) throws Exception {
//        InputStream inStream = new FileInputStream(file);
//        uploadFile(inStream, filePath);
//    }
//
//    /**
//     * 上传文件到ftp
//     *
//     * @param inStream 上传的文件流
//     * @param filePath 上传路径
//     * @throws Exception
//     */
//    public void uploadFile(InputStream inStream, String filePath)
//            throws Exception {
//        if (inStream == null) {
//            return;
//        }
//        String fileName = "";
//        filePath = StringUtils.removeStart(filePath, "/");
//        int len = filePath.lastIndexOf("/");
//        if (len == -1) {
//            if (filePath.length() > 0) {
//                fileName = filePath;
//            } else {
//                throw new Exception("没有输入文件路径");
//            }
//        } else {
//            fileName = filePath.substring(len + 1);
//            String type = filePath.substring(0, len);
//            String[] typeArray = type.split("/");
//            for (String s : typeArray) {
//                s.trim();
//                if (!checkDirectory(ftp, s)) {
//                    if(!ftp.existsDirectory(s)) {
//                        ftp.mkdir(s);
//                    }
//                    changeDirectory(s);
//                }
//            }
//        }
//        ftp.put(inStream, fileName);
//        changeDirectory("/");
//    }
//
//    public void uploadFile2(File inFile,String fileName) throws IOException, FTPException {
//        InputStream inStream = new FileInputStream(inFile);
//        ftp.put(inStream, fileName);
//    }
//
//    /**
//     * 删除ftp文件
//     *
//     * @param filePath 文件路径
//     * @throws Exception
//     */
//    public void deleteFile(String filePath) throws Exception {
//        String fileName = "";
//        filePath = StringUtils.removeStart(filePath, "/");
//        int len = filePath.lastIndexOf("/");
//        if (len == -1) {
//            if (filePath.length() > 0) {
//                fileName = filePath;
//            } else {
//                throw new Exception("没有输入文件路径");
//            }
//        } else {
//            fileName = filePath.substring(len + 1);
//
//            String type = filePath.substring(0, len);
//            String[] typeArray = type.split("/");
//            for (String s : typeArray) {
//                if (checkDirectory(ftp, s)) {
//                    ftp.chdir(s);
//                }
//            }
//        }
//        ftp.delete(fileName);
//    }
//
//
//     //切换目录
//    public void changeDirectory(String path) {
//        if (!StringUtils.isEmpty(path)) {
//            try {
//                ftp.chdir(path);
//            } catch (Exception e) {
//                e.printStackTrace();
//            }
//        }
//    }
//
//    //读取文件列表
//    public List<File> getFileList(String path) {
//        List<File> rsList = new ArrayList<>();
//        if (path == null || path.equals("")) {
//            return rsList;
//        }
//        File file = new File(path);
//        if (!file.exists()) {
//            return rsList;
//        }
//        // 处理文件
//        if (file.isFile()) {
//            rsList.add(file);
//            return rsList;
//        }
//        // 处理文件夹
//        if (null == file.listFiles()) {
//            rsList.add(file);
//            return rsList;
//        }
//        LinkedList<File> forDealList = new LinkedList<>();
//        forDealList.addAll(Arrays.asList(file.listFiles()));
//        while (!forDealList.isEmpty()) {
//            File firstFile = forDealList.removeFirst();
//            // 处理文件
//            if (firstFile.isFile()) {
//                // 把文件自身先加入结果
//                rsList.add(firstFile);
//                continue;
//            }
//            // 处理文件夹
//            File[] files = firstFile.listFiles();
//            if (files == null) {
//                continue;
//            }
//            for (File curr : files) {
//                if (curr.isDirectory()) {
//                    // 将此文件夹放入待处理列表
//                    forDealList.add(curr);
//                } else {
//                    rsList.add(curr);
//                }
//            }
//        }
//        return rsList;
//    }
//
//    public void deleteDir(String dirName) throws IOException, FTPException, ParseException {
//        FTPClient client = ftp;
//
//        //String[] dir = client.dir(dirName, true);
//        FTPFile[] ftpFiles = client.dirDetails(dirName);
//        for (FTPFile ftpFile : ftpFiles) {
//            if(ftpFile.isDir()){
//                deleteDir(dirName+"/"+ftpFile.getName());
//            }else{
//                client.delete(dirName+"/"+ftpFile.getName());
//            }
//        }
//        /*for (String subDirName : dir) {
//            String name = subDirName.substring(subDirName.lastIndexOf(" ") + 1);
//            if(subDirName.contains("<DIR>")){ //文件夹
//                //name = new String(name.getBytes(StandardCharsets.ISO_8859_1),"GBK");
//                deleteDir(dirName+"/"+name);
//                //client.rmdir(dirName+"/"+name);
//            }else{
//                //name = new String(name.getBytes(StandardCharsets.ISO_8859_1),"GBK");
//                client.delete(dirName+"/"+name);
//            }
//        }*/
//        client.rmdir(dirName);
//    }
//
//    public String[] getDirList() throws IOException, FTPException {
//        return ftp.dir();
//    }
//
//    public void mkdir(String dirPath) throws IOException, FTPException {
//        ftp.mkdir(dirPath);
//    }
//}
src/main/java/com/whyc/service/FtpService.java
@@ -1,82 +1,86 @@
package com.whyc.service;
import com.enterprisedt.net.ftp.FTPException;
import com.whyc.constant.YamlProperties;
import com.whyc.dto.FileDirPath;
import com.whyc.dto.FtpHelper;
import com.whyc.dto.ZipUtils;
import com.whyc.util.ActionUtil;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ConditionalOnProperty(prefix = "configFile",name = "type",havingValue = "2")
@Service
@EnableScheduling   // 2.开启定时任务
public class FtpService {
    //定时上传指定目录下文件,每周五凌晨开启备份
    @Scheduled(cron = "59 59 23 ? * FRI")
    //@Scheduled(cron = "0 29 15 * * ?")
    public void sendFtpFile() throws IOException, FTPException, ParseException {
        //先连接ftp服务器
        FtpHelper ftpRemote = new FtpHelper(YamlProperties.ftpIp, YamlProperties.ftpPort, YamlProperties.ftpUserName, YamlProperties.ftpPassword);
        String fileDirName = FileDirPath.getFileDirName();
        String rootDoc=fileDirName+File.separator+"doc_file";
        String timeStr= ActionUtil.sdfwithFTP.format(new Date());
        ftpRemote.mkdir(timeStr);
        //备份过程是否出现过问题,标识符
        boolean isError=false;
        try {
            File docFile = new File(rootDoc);
            File[] fileList = docFile.listFiles();
            //File[] fileList2 = new File[fileList.length];
            //BeanUtils.copyProperties(fileList2,fileList);
            for (File file:fileList) {
                //压缩传输
                File fileZip = new File(file.getAbsolutePath() + ".zip");
                ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
                //System.out.println(fileZip.toString()+"压缩完毕");
                //System.out.println("进行FTP传输中...");
                try {
                    //ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
                    String pathName=timeStr+"/"+file.getName()+".zip";
                    //System.out.println("传输目标路径确认为:"+pathName);
                    ftpRemote.uploadFile2(fileZip, pathName);
                    //System.out.println(fileZip+"传输完毕");
                    fileZip.delete();
                    //System.out.println(fileZip+"传输中转压缩包删除完毕");
                } catch (Exception e) {
                    isError = true;
                    e.printStackTrace();
                    fileZip.delete();
                }
            }
            //System.out.println("传输完毕");
            //获取备份目录,保留4次.
            //如果过程出现错误,则不删除
            if (!isError) {
                String[] dirList = ftpRemote.getDirList();
                List<String> dirList2 = Arrays.asList(dirList);
                for (int i = 0; i < dirList2.size()-4; i++) {
                    ftpRemote.deleteDir(dirList2.get(i));
                }
            }
        } catch (Exception e) {
        }finally {
            ftpRemote.disconnect();
        }
    }
}
//package com.whyc.service;
//
//import com.enterprisedt.net.ftp.FTPException;
//import com.whyc.constant.YamlProperties;
//import com.whyc.dto.FileDirPath;
//import com.whyc.dto.FtpHelper;
//import com.whyc.dto.ZipUtils;
//import com.whyc.util.ActionUtil;
//import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
//import org.springframework.scheduling.annotation.EnableScheduling;
//import org.springframework.scheduling.annotation.Scheduled;
//import org.springframework.stereotype.Service;
//
//import java.io.File;
//import java.io.FileOutputStream;
//import java.io.IOException;
//import java.text.ParseException;
//import java.util.Arrays;
//import java.util.Date;
//import java.util.List;
//
//@ConditionalOnProperty(prefix = "configFile",name = "type",havingValue = "2")
//@Service
//@EnableScheduling   // 2.开启定时任务
//public class FtpService {
//    //定时上传指定目录下文件,每周五凌晨开启备份
//    //@Scheduled(cron = "59 59 23 ? * FRI")
//    @Scheduled(cron = "0 30 8 * * ?")
//    public void sendFtpFile() throws IOException, FTPException, ParseException {
//        //先连接ftp服务器
//        FtpHelper ftpRemote = new FtpHelper(YamlProperties.ftpIp, YamlProperties.ftpPort, YamlProperties.ftpUserName, YamlProperties.ftpPassword);
//        String fileDirName = FileDirPath.getFileDirName();
//        String rootDoc=fileDirName+File.separator+"doc_file";
//        String timeStr= ActionUtil.sdfwithFTP.format(new Date());
//        ftpRemote.mkdir(timeStr);
//        ftpRemote.disconnect();
//        //备份过程是否出现过问题,标识符
//        boolean isError=false;
//        try {
//
//            File docFile = new File(rootDoc);
//            File[] fileList = docFile.listFiles();
//            //File[] fileList2 = new File[fileList.length];
//            //BeanUtils.copyProperties(fileList2,fileList);
//            for (File file:fileList) {
//                FtpHelper ftpTemp = new FtpHelper(YamlProperties.ftpIp, YamlProperties.ftpPort, YamlProperties.ftpUserName, YamlProperties.ftpPassword);
//                //压缩传输
//                File fileZip = new File(file.getAbsolutePath() + ".zip");
//                ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
//                //System.out.println(fileZip.toString()+"压缩完毕");
//                //System.out.println("进行FTP传输中...");
//                try {
//                    //ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
//                    String pathName=timeStr+"/"+file.getName()+".zip";
//                    //System.out.println("传输目标路径确认为:"+pathName);
//                    ftpTemp.uploadFile2(fileZip, pathName);
//                    //System.out.println(fileZip+"传输完毕");
//                    fileZip.delete();
//                    //System.out.println(fileZip+"传输中转压缩包删除完毕");
//                } catch (Exception e) {
//                    isError = true;
//                    e.printStackTrace();
//                    fileZip.delete();
//                }finally {
//                    ftpTemp.disconnect();
//                }
//            }
//            //System.out.println("传输完毕");
//
//            //获取备份目录,保留4次.
//            //如果过程出现错误,则不删除
//            if (!isError) {
//                FtpHelper ftpTemp = new FtpHelper(YamlProperties.ftpIp, YamlProperties.ftpPort, YamlProperties.ftpUserName, YamlProperties.ftpPassword);
//                String[] dirList = ftpRemote.getDirList();
//                List<String> dirList2 = Arrays.asList(dirList);
//
//                for (int i = 0; i < dirList2.size()-4; i++) {
//                    ftpTemp.deleteDir(dirList2.get(i));
//                }
//                ftpTemp.disconnect();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//}
src/main/java/com/whyc/service/FtpService2.java
New file
@@ -0,0 +1,95 @@
package com.whyc.service;
import com.whyc.dto.FTPClientUtil;
import com.whyc.dto.FileDirPath;
import com.whyc.dto.ZipUtils;
import com.whyc.util.ActionUtil;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
@ConditionalOnProperty(prefix = "configFile",name = "type",havingValue = "2")
@Service
@EnableScheduling   // 2.开启定时任务
public class FtpService2 {
    //定时上传指定目录下文件,每周五凌晨开启备份
    @Scheduled(cron = "59 59 23 ? * FRI")
    public void sendFtpFile() throws IOException {
        //先连接ftp服务器
        FTPClient client = FTPClientUtil.connect();
        String fileDirName = FileDirPath.getFileDirName();
        String rootDoc=fileDirName+File.separator+"doc_file";
        String timeStr= ActionUtil.sdfwithFTP.format(new Date());
        client.makeDirectory(timeStr);
        client.disconnect();
        //备份过程是否出现过问题,标识符
        boolean isError=false;
        try {
            File docFile = new File(rootDoc);
            File[] fileList = docFile.listFiles();
            //File[] fileList2 = new File[fileList.length];
            //BeanUtils.copyProperties(fileList2,fileList);
            for (File file:fileList) {
                //压缩传输
                File fileZip = new File(file.getAbsolutePath() + ".zip");
                ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
                //System.out.println(fileZip.toString()+"压缩完毕");
                //System.out.println("进行FTP传输中...");
                try {
                    //ZipUtils.toZip(file.getAbsolutePath(),new FileOutputStream(fileZip),true);
                    String pathName=timeStr+"/"+file.getName()+".zip";
                    //System.out.println("传输目标路径确认为:"+pathName);
                    FTPClientUtil.transferFile(fileZip, pathName);
                    //System.out.println(fileZip+"传输完毕");
                    fileZip.delete();
                    //System.out.println(fileZip+"传输中转压缩包删除完毕");
                } catch (Exception e) {
                    isError = true;
                    e.printStackTrace();
                    fileZip.delete();
                }
            }
            //System.out.println("传输完毕");
            //获取备份目录,保留4次.
            //如果过程出现错误,则不删除
            if (!isError) {
                FTPClient client2 = FTPClientUtil.connect();
                String[] dirList = client2.listNames();
                List<String> dirList2 = Arrays.asList(dirList);
                for (int i = 0; i < dirList2.size()-4; i++) {
                    String dirToBeDelete = dirList2.get(i);
                    if(!client2.removeDirectory(dirToBeDelete)){
                        // 删除失败,可以尝试递归删除目录内的所有内容
                        FTPFile[] subFiles = client2.listFiles(dirToBeDelete);
                        if (subFiles != null && subFiles.length > 0) {
                            for (FTPFile subFile : subFiles) {
                                if (!subFile.isDirectory()) {
                                    // 删除文件
                                    client2.deleteFile(dirToBeDelete + "/" + subFile.getName());
                                }
                            }
                            // 再次尝试删除目录
                            client2.removeDirectory(dirToBeDelete);
                        }
                    }
                }
                client2.disconnect();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}