首页 > 解决方案 > 如何在java中压缩一组给定的文件

问题描述

给定一组文件的位置,我想压缩一组文件。

将该 Zip 文件发送到下面提到的方法

private StreamingOutput buildStreamingOutput(final File pdfFile, final boolean isGeneratedPdf) {
        return new StreamingOutput() {
            @Override
            public void write(OutputStream output) throws IOException, WebApplicationException {
                java.nio.file.Path path = Paths.get(pdfFile.getAbsolutePath());
                byte[] data = CryptoUtil.decryptAsByteArray(path);
                output.write(data);
                output.flush();
                output.close();
                if (isGeneratedPdf) {
                    pdfFile.delete();
                }
            }
        };
    }

是否可以压缩文件并将该 Zip 文件作为文件(File.class)发送

标签: javazip

解决方案


愿对你有用。

使用下面的代码:

         public void buildStreamingOutput(HttpServletResponse 
              resp,java.util.List<File> files) throws IOException {
              ZipOutputStream  zipOutstream = new 
              ZipOutputStream(resp.getOutputStream());
           resp.setContentType("application/octet-stream");
           resp.setHeader("Content-Disposition", "attachment; filename= 
        {zipfilename.zip}");

           for(File file : files) {
               appendFileToZIP(zipOutstream,file);
           }

       }


       public void appendFileToZIP( ZipOutputStream _zipOutstream  ,final File pdfFile) {

            int nlength = 0;

            FileInputStream fis = null;
            DataInputStream disObj = null;

            try {

                if (!pdfFile.exists()) {
                    System.out.println(" file does not exists "+pdfFile.getName());
                    return;
                }

                fis = new FileInputStream(pdfFile);

                _zipOutstream.putNextEntry(new ZipEntry(pdfFile.getName()));

                disObj = new DataInputStream(fis);

                byte[] bbuf = new byte[1024];
                while ((disObj != null) && ((nlength = disObj.read(bbuf)) != -1)) {
                    _zipOutstream.write(bbuf, 0, nlength);
                }
                _zipOutstream.flush();

            } catch (IOException e) {

            } catch (Exception e) {

            } finally {
                try {
                    fis.close();
                } catch (Exception e) {

                }

            }
        }

推荐阅读