ZipUtil 压缩文件并用Spring Integration sftp 上传FTP
ZipUtil:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 | 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(); } } |
上报:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | 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方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @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); } } |
获取上报路径:
1 2 3 4 5 6 7 8 | //获取上报路径 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) //自定义随便写<br> .append(date); <br> return builder.toString(); <br>} |
导入jar(版本就选4.3.17吧):
1 2 3 4 5 6 7 8 | <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配置:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | @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; } |
配置:
1 2 3 4 5 6 7 8 9 10 | upload: ftp: host: 127.0 . 0.1 port: 21 userName: root password: root remoteDirectory: '' temporaryFileSuffix: .tmp useTemporaryFileName: true autoCreateDirectory: true |
分类:
Spring
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· AI 智能体引爆开源社区「GitHub 热点速览」
· 写一个简单的SQL生成工具