java 通过ZipOutputStream压缩多个文件并转成流上传sftp

项目场景:

场景:有时候我们会遇到需要将sftp上的多个文件压缩成zip再上传到sftp上保存。


相关代码


    public void saveZipFile(XXX xxx, List<String> fileUrlList) {

        try {
            // 其他逻辑
            ....
            
            InputStream inputStream = compressFiles(fileUrlList);

            boolean success = fileSystemService.uploadFile(filePath, inputStream);
            if (success) {
                // 其他逻辑
                .....
                }
            }

        } catch (Exception e) {
            log.error("saveZipFile failed, caused by: {}", e.getMessage(), e);
        }
    }

    public InputStream compressFiles(List<String> fileUrlList) throws Exception {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
             ZipOutputStream out = new ZipOutputStream(baos)) {
            for (String fileUrl : fileUrlList) {
                compressFile(out, fileUrl);
            }
            
            // 之前因为没有加这句导致生成的压缩包一直无法打开,找了很久原因才找到
            out.finish();
            
            return new ByteArrayInputStream(baos.toByteArray());
        }
    }

    public void compressFile(ZipOutputStream out, String fileUrl) throws Exception {
        try (InputStream fileContent = fileSystemService.downloadFileAsInputStream(String.format("%s%s", config.getRoot(), fileUrl))) {
            ZipEntry zipEntry = new ZipEntry(fileUrl.substring(fileUrl.lastIndexOf('/') + 1));
            out.putNextEntry(zipEntry);

            byte[] buffer = new byte[1024];
            int length;
            while ((length = fileContent.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
            out.closeEntry();
        }
    }

部分内容解释:

fileUrlList:是sftp上的文件地址;
InputStream fileContent = fileSystemService.downloadFileAsInputStream(String.format(“%s%s”, config.getRoot(), fileUrl)):是从sftp上下载并把文件转成输入流;


其余代码如下:

    // 下载文件并转成输入流
    @Override
    public InputStream downloadFileAsInputStream(String targetPath) throws Exception {
        ChannelSftp sftp = this.createSftp();
        try (ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream()) {
            sftp.cd(config.getRoot());
            log.info("Change path to {}", config.getRoot());
            sftp.get(targetPath, byteArrayOutputStream);
            InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
            log.info("Download file success. TargetPath: {}", targetPath);
            return inputStream;
        } catch (Exception e) {
            log.error("Download file failure. TargetPath: {}", targetPath, e);
            throw new ServiceException("Download File failure");
        } finally {
            this.disconnect(sftp);
        }
    }

     // 上传生成的zip文件
    @Override
    public boolean uploadFile(String targetPath, InputStream inputStream) throws Exception {
        ChannelSftp sftp = this.createSftp();
        try {
            sftp.cd(config.getRoot());
            log.info("Change path to {}", config.getRoot());
            int index = targetPath.lastIndexOf("/");
            String fileDir = targetPath.substring(0, index);
            String fileName = targetPath.substring(index + 1);
            boolean dirs = this.createDirs(fileDir, sftp);
            if (!dirs) {
                log.error("Remote path error. path:{}", targetPath);
                throw new Exception("Upload File failure");
            }
            sftp.put(inputStream, fileName);
            return true;
        } catch (Exception e) {
            log.error("Upload file failure. TargetPath: {}", targetPath, e);
            throw new ServiceException("Upload File failure");
        } finally {
            this.disconnect(sftp);
        }
    }

总结:

以上就是把sftp的文件下载压缩并上传的大致内容,整体和本地压缩文件差别不大,就是在不熟悉的情况下被压缩文件打不开问题困扰了很久,所以记录一下,希望能给同样碰到这个问题的伙伴一点帮助!;

### 回答1: 可以使用JavaZipOutputStream类来压缩多个文件,然后将压缩后的内容写入ByteArrayOutputStream中。接着可以使用ByteArrayOutputStream的toByteArray()方法获取压缩后的字节数组,并将其作为响应进行下载。 示例代码如下: ``` List<File> filesToZip = Arrays.asList(new File("file1.txt"), new File("file2.txt")); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ZipOutputStream zos = new ZipOutputStream(baos); for (File file : filesToZip) { ZipEntry entry = new ZipEntry(file.getName()); zos.putNextEntry(entry); byte[] bytes = Files.readAllBytes(file.toPath()); zos.write(bytes, 0, bytes.length); zos.closeEntry(); } zos.close(); byte[] zippedBytes = baos.toByteArray(); ``` 最后使用response的方式下载 zippedBytes ### 回答2: Java提供了ZipOutputStream类用于压缩文件文件夹,ByteArrayOutputStream类用于将数据写入内存缓冲区中的字节数组。 以下是使用ZipOutputStream压缩多个文件并转换为ByteArrayOutputStream进行下载的示例代码: ```java import java.io.*; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class ZipMultipleFilesToByteArrayOutputStreamExample { public static void main(String[] args) { try { // 创建ByteArrayOutputStream对象 ByteArrayOutputStream baos = new ByteArrayOutputStream(); // 创建ZipOutputStream对象,并将其与ByteArrayOutputStream关联 ZipOutputStream zipOut = new ZipOutputStream(baos); // 需要压缩文件列表 String[] filesToCompress = {"file1.txt", "file2.txt", "file3.txt"}; // 遍历文件列表,逐个进行压缩 for (String fileName : filesToCompress) { // 创建输入流读取文件内容 FileInputStream fis = new FileInputStream(fileName); // 添加文件压缩包 zipOut.putNextEntry(new ZipEntry(fileName)); // 将文件内容写入ZipOutputStream byte[] buffer = new byte[1024]; int length; while ((length = fis.read(buffer)) > 0) { zipOut.write(buffer, 0, length); } // 关闭当前文件的输入流 fis.close(); } // 关闭ZipOutputStream zipOut.close(); // 将ByteArrayOutputStream换为字节数组 byte[] zipBytes = baos.toByteArray(); // 下载字节数组或保存为文件等操作 // ... } catch (IOException e) { e.printStackTrace(); } } } ``` 以上代码示例实现了将多个文件压缩为一个ZIP文件,并将压缩结果换为ByteArrayOutputStream。你可以根据需要将压缩结果进行下载或保存为文件等操作。 ### 回答3: 在Java中,可以使用ZipOutputStream类来实现多个文件压缩,并将其换为ByteArrayOutputStream对象进行下载。 首先,需要导入相关的Java IO库和ZipOutputStream类: ```java import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; ``` 接下来,创建一个ByteArrayOutputStream对象,用于接收ZipOutputStream的输出: ```java ByteArrayOutputStream baos = new ByteArrayOutputStream(); ``` 然后,创建一个ZipOutputStream对象,并绑定到ByteArrayOutputStream上: ```java ZipOutputStream zipOut = new ZipOutputStream(baos); ``` 接着,遍历多个文件,将每个文件逐个添加到ZipOutputStream中: ```java File file1 = new File("file1.txt"); File file2 = new File("file2.txt"); addToZip(zipOut, file1); addToZip(zipOut, file2); // 将文件添加到ZipOutputStream中的方法 private static void addToZip(ZipOutputStream zipOut, File file) throws Exception { FileInputStream fis = new FileInputStream(file); ZipEntry zipEntry = new ZipEntry(file.getName()); zipOut.putNextEntry(zipEntry); byte[] bytes = new byte[1024]; int length; while ((length = fis.read(bytes)) >= 0) { zipOut.write(bytes, 0, length); } zipOut.closeEntry(); fis.close(); } ``` 压缩后,关闭ZipOutputStream和ByteArrayOutputStream: ```java zipOut.close(); baos.close(); ``` 最后,将ByteArrayOutputStream换为byte数组并进行下载: ```java byte[] zipBytes = baos.toByteArray(); // 将byte数组进行下载的代码,这里省略 ``` 以上就是使用Java ZipOutputStream压缩多个文件,并将其换为ByteArrayOutputStream进行下载的步骤。注意要逐个添加文件ZipOutputStream中,并在最后关闭相关的流对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值