要将多个文件压缩为一个压缩包后下载,可以使用Java的ZipOutputStream类。下面是一个示例代码:

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class FileDownloader {
    public static void main(String[] args) {
        String[] fileList = {"file1.txt", "file2.txt", "file3.txt"}; // 要压缩的文件列表

        try {
            // 创建一个临时文件用于存放压缩包
            File tempFile = File.createTempFile("temp", ".zip");
            FileOutputStream fos = new FileOutputStream(tempFile);
            ZipOutputStream zos = new ZipOutputStream(fos);

            // 遍历文件列表
            for (String fileName : fileList) {
                File file = new File(fileName);
                FileInputStream fis = new FileInputStream(file);
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);

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

                fis.close();
            }

            zos.closeEntry();
            zos.close();

            // 提供下载
            FileInputStream fis = new FileInputStream(tempFile);
            OutputStream os = new BufferedOutputStream(new FileOutputStream("download.zip"));
            byte[] buffer = new byte[1024];
            int length;
            while ((length = fis.read(buffer)) > 0) {
                os.write(buffer, 0, length);
            }
            os.flush();
            os.close();
            fis.close();

            // 删除临时文件
            tempFile.delete();

            System.out.println("压缩包下载成功!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

上述代码将指定的文件列表压缩为一个临时的压缩包文件,然后将该文件提供给用户进行下载。你可以根据需要修改文件列表和下载路径

java fileoutputstream的list放在压缩包后下载

原文地址: https://www.cveoy.top/t/topic/iYKD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录