多文件byte[]压缩zip


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

//依赖的包
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class TestController {
    @RequestMapping("/zip")
    public void code( HttpServletResponse response) throws IOException {
        byte[] fileByte1 = readBytesFromFile("/Users/lgb/test1.txt");
        byte[] fileByte2 = readBytesFromFile("/Users/lgb/test2.txt");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        //TODO 下面可以做循环压缩,这里只做演示
        
        //添加到zip
        //一定要加目录
        zip.putNextEntry(new ZipEntry("test" + File.separator + "test1.txt""));
        IOUtils.write(fileByte1, zip);
        zip.closeEntry();

        zip.putNextEntry(new ZipEntry("test" + File.separator + "test2.txt""));
        IOUtils.write(fileByte2, zip);
        zip.closeEntry();
            
        IOUtils.closeQuietly(zip);
        byte[] data = outputStream.toByteArray();

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"你想要的名称.zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");
        
        IOUtils.write(data, response.getOutputStream());
    }

 	/***
 	 * 文件转换为byte[]
 	 */
    private static byte[] readBytesFromFile(String filePath) {
        FileInputStream fileInputStream = null;
        byte[] bytesArray = null;
        try {
            File file = new File(filePath);
            bytesArray = new byte[(int) file.length()];

            //read file into bytes[]
            fileInputStream = new FileInputStream(file);
            fileInputStream.read(bytesArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return bytesArray;
    }
}

你可能感兴趣的:(java小技巧)