ZipUtil 压缩文件并用Spring Integration sftp 上传FTP

ZipUtil:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

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.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author 47Gamer
 * @date: 2019/11/11 14:47
 * @Description:
 */
public class ZipUtil {
    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);
    private static final String TARGET_PACKAGE = "target";

    public static void exportZip(OutputStream out, String rootPath, String fileName) {

        File zipfile = null;
        File targetDirectory = null;
        InputStream fin = null;
        String source = rootPath + File.separator + fileName;
        String target = rootPath + File.separator + TARGET_PACKAGE;
        String targetFile = target + File.separator + fileName + ".zip";
        try {
            targetDirectory = new File(target);
            targetDirectory.mkdirs();
            //压缩目录
            ZipUtil.createZip(source, targetFile);
            //根据路径获取刚生成的zip包文件
            zipfile = new File(targetFile);
            fin = new FileInputStream(zipfile);
            byte[] buffer = new byte[512]; // 缓冲区
            int bytesToRead = -1;
            // 通过循环将读入的Word文件的内容输出到浏览器中
            while ((bytesToRead = fin.read(buffer)) != -1) {
                out.write(buffer, 0, bytesToRead);
            }
        } catch (Exception e) {
            logger.error("ZipUtils exportZip error:" + e.getMessage());
        } finally {
            try {
                if (fin != null) fin.close();
                if (out != null) out.close();
                if (zipfile != null) {
                    zipfile.delete();
                }
                if (targetDirectory != null) {
                    //递归删除目录及目录下文件
                    ZipUtil.deleteFile(targetDirectory);
                }
            } catch (Exception e2) {
                logger.error("ZipUtils closing stream error:" + e2.getMessage());
            }

        }
    }

    /**
     * 创建ZIP文件
     *
     * @param sourcePath 文件或文件夹路径
     * @param zipPath    生成的zip文件存在路径(包括文件名)
     */
    public static void createZip(String sourcePath, String zipPath) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);
            writeZip(new File(sourcePath), "", zos);
        } catch (FileNotFoundException e) {
            logger.error("ZipUtils createZip  Failed to create ZIP file", e);
        } finally {
            try {
                if (zos != null) {
                    logger.debug("ZipUtils createZip Create a ZIP file successfully! the path in:{}", zipPath);
                    zos.close();
                }
            } catch (IOException e) {
                logger.error("ZipUtils createZip  Failed to create ZIP file", e);
            }
        }
    }

    private static void writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.exists()) {
            if (file.isDirectory()) {// 处理文件夹
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                if (Objects.nonNull(files)){
                    for (File f : files) {
                        writeZip(f, parentPath, zos);
                    }
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[1024];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        zos.write(content, 0, len);
                        zos.flush();
                    }
                } catch (IOException e) {
                    logger.error("ZipUtils createZip  Failed to create ZIP file", e);
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        logger.error("ZipUtils createZip  Failed to create ZIP file", e);
                    }
                }
            }
        }
    }

    /**
     * 删除文件夹
     *
     * @param file
     */
    public static void deleteFile(File file) {
        if (Objects.isNull(file) || !file.exists()){
            return;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (Objects.nonNull(files)){
                for (File subFile : files) {
                    deleteFile(subFile);
                }
            }
        }
        file.delete();
    }
}

 上报:

private static final String CACHE_ROOT = "自定义文件路径";

    //生成文件到缓存目录,压缩上报
    private void cacheAndUploadFile(List<Object> list, String fileName, String uploadPath) {
        //生成UUID(可自己写,代码就不贴出来了)
        String uuid = IdUtil.generateUUID();
        String dir = CACHE_ROOT + File.separator + uuid;
        File dirFile = new File(dir);
        String csvFullName = dir + File.separator + fileName + ".csv";
        String excelFullName = dir + File.separator + fileName + ".xls";
        String zipName = fileName + ".csv.zip";
        String zipFullName = dir + File.separator + zipName;
        //生成xml文件到缓存目录
        if (!dirFile.exists()) {
            dirFile.mkdirs();
        }
        //转换Excel
        //covertToExcel(list, dir, fileName + ".xls");
        //POIUtil.excel2Csv(excelFullName, csvFullName);
        //压缩为zip文件
        ZipUtil.createZip(csvFullName, zipFullName);
        //上报
        upload(zipFullName, uploadPath);
        //删除缓存文件
        ZipUtil.deleteFile(dirFile);
    }

 upload方法:

 @Autowired
 RemoteFileTemplate remoteFileTemplate;

  //上报
  private void upload(String sourceFullName, String uploadPath) {
        File sourceFile = new File(sourceFullName);
        try {
            Message<File> message = MessageBuilder.withPayload(sourceFile).build();
            remoteFileTemplate.send(message, uploadPath);
        } catch (Exception e) {
            logger.error("Upload file error, sourceFullName[{}], uploadPath[{}]", sourceFullName, uploadPath, e);
        }
   }

 获取上报路径:

//获取上报路径
private String getFilePath(String city, String vendor, String date) {
        String remoteFileSeparator = remoteFileTemplate.getRemoteFileSeparator();
        StringBuilder builder = new StringBuilder();
        builder
                .append(remoteDirectory).append(remoteFileSeparator)//remoteDirectory为FTP文件路径
                .append("var").append(remoteFileSeparator) //自定义随便写
                .append("file").append(remoteFileSeparator)//自定义随便写
          .append(date);
    return builder.toString();
}

 导入jar(版本就选4.3.17吧):

<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-integration</artifactId>
</dependency>
<dependency>
	<groupId>org.springframework.integration</groupId>
	<artifactId>spring-integration-ftp</artifactId>
</dependency>

FTP配置:

@Configuration
public class Ftpconfig {

    @Value("${upload.ftp.host}")
    private String host;
    @Value("${upload.ftp.port}")
    private int port;
    @Value("${upload.ftp.userName}")
    private String userName;
    @Value("${upload.ftp.password}")
    private String password;
    @Value("${upload.ftp.remoteDirectory}")
    private String remoteDirectory;
    @Value("${upload.ftp.temporaryFileSuffix}")
    private String temporaryFileSuffix;
    @Value("${upload.ftp.useTemporaryFileName}")
    private boolean useTemporaryFileName;
    @Value("${upload.ftp.autoCreateDirectory}")
    private boolean autoCreateDirectory;

    @Bean
    public SessionFactory<FTPFile> ftpSessionFactory() {
        DefaultFtpSessionFactory factory = new DefaultFtpSessionFactory();
        factory.setHost(host);
        factory.setPort(port);
        factory.setUsername(userName);
        factory.setPassword(password);
        return new CachingSessionFactory<FTPFile>(factory);
    }

    @Bean
    public RemoteFileTemplate remoteFileTemplate(){
        RemoteFileTemplate template = new FtpRemoteFileTemplate(ftpSessionFactory());
        template.setRemoteDirectoryExpression(new LiteralExpression(remoteDirectory));
        template.setTemporaryFileSuffix(temporaryFileSuffix);
        template.setUseTemporaryFileName(useTemporaryFileName);
        template.setAutoCreateDirectory(autoCreateDirectory);

        return template;
    }

 配置:

upload:
  ftp:
    host: 127.0.0.1
    port: 21
    userName: root
    password: root
    remoteDirectory: ''
    temporaryFileSuffix: .tmp
    useTemporaryFileName: true
    autoCreateDirectory: true
原文地址:https://www.cnblogs.com/47Gamer/p/13684491.html