Use Java to download and compress files in zip format

Written in the front : I am "Sailing to the Sea" . This nickname comes from my name and the name of my girlfriend. I love technology, open source, and programming. 技术是开源的、知识是共享的.

This blog is a little summary and record of your own learning. If you are interested in Java and algorithms , you can follow my dynamics and we will learn together.

用知识改变命运,让我们的家人过上更好的生活.

I haven't written an article for more than two months due to my busy schedule. In the recent development, the slave server is used to download files to the local in the form of compressed packages. Here is a summary. If you need to use it, you can directly use it as a tool!


1. Batch download files in zip format

Steps :

① Obtain the OutputStream stream through the response object
② Set the content type of the file to determine the download file type
③ Set the file header
④ Get the output stream of the zip
⑤ Get all the folders and files under the file path
⑥ Get all the file names and directories under this directory Name
⑦ Read the file path collection cyclically to obtain the path of each file
⑧ Create a file through the file path
⑨ Write each file into the zip file compression package, that is, pack it
⑩ Finally refresh the buffer

Code:

/**
 * 以zip形式批量下载文件
 *
 * @param response
 * @param downloadName
 * @param filePath
 */
public static void MultiFileZipDownload(HttpServletResponse response, String downloadName, String filePath) {
    
    
    OutputStream outputStream = null;
    ZipOutputStream zos = null;
    try {
    
    
        // 通过response对象获取OutputStream流
        outputStream = response.getOutputStream();
        // 设置文件ContentType类型
        response.setContentType("multipart/form-data");
        // 设置文件头
        response.setHeader("Content-Disposition", "attachment;fileName = " + URLEncoder.encode(downloadName, "UTF-8"));
        // 获取zip的输出流
        zos = new ZipOutputStream(outputStream);
        // 获取文件路径下的所有文件夹及文件
        File dirFile = new File(filePath);
        // 获取此目录下的所有文件名与目录名
        String[] fileList = dirFile.list();
        // 循环读取文件路径集合,获取每一个文件的路径
        if (fileList != null) {
    
    
            for (String fp : fileList) {
    
    
                File file = new File(filePath, fp);  // 通过文件路径创建文件
                zipFile(file, zos);  // 将每一个文件写入zip文件压缩包内,即进行打包
                // 刷新缓冲区
                response.flushBuffer();
            }
        }
    } catch (Exception e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        try {
    
    
            if (zos != null) {
    
    
                zos.close();
            }
            if (outputStream != null) {
    
    
                outputStream.close();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

Second, the method of compressing files

Steps :

① First determine whether the file exists
② If it is a file
③ Create an input stream to read the file
④ Write the file into the zip archive
⑤ Write to the file
⑥ Finally close the input and output streams
⑦ If it is a folder, use exhaustion Method to get the file and write it into the zip archive
⑧ Close the input and output streams

Code:

/**
 * 压缩文件的方法
 *
 * @param inputFile
 * @param zipoutputStream
 */
public static void zipFile(File inputFile, ZipOutputStream zipoutputStream) {
    
    
    FileInputStream fis = null;
    BufferedInputStream bis = null;
    try {
    
    
        if (inputFile.exists()) {
    
     // 判断文件是否存在
            if (inputFile.isFile()) {
    
      // 如果是文件
                // 创建输入流读取文件
                fis = new FileInputStream(inputFile);
                bis = new BufferedInputStream(fis);
                // 将文件写入zip压缩包内
                ZipEntry zip =
                        new ZipEntry(inputFile.getParentFile().getName() + File.separator + inputFile.getName()); //获取文件名
                zipoutputStream.putNextEntry(zip);
                // 进行写入文件
                byte[] bytes = new byte[1024];
                long fileLength = 0;
                while (fileLength < inputFile.length()) {
    
    
                    int count = bis.read(bytes, 0, 1024);
                    fileLength += count;
                    zipoutputStream.write(bytes, 0, count);
                }
                // 关闭输入输出流
                if (bis != null) {
    
    
                    bis.close();
                }
                if (fis != null) {
    
    
                    fis.close();
                }
            } else {
    
      // 如果是文件夹,则使用穷举的方法获取文件,写入zip
                try {
    
    
                    zipoutputStream.putNextEntry(new ZipEntry(inputFile.getName() + File.separator));
                    File[] files = inputFile.listFiles();
                    for (int i = 0; i < files.length; i++) {
    
    
                        zipFile(files[i], zipoutputStream);
                    }
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
            }
        }
    } catch (Exception e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        try {
    
    
            if (bis != null) {
    
    
                bis.close();
            }
            if (fis != null) {
    
    
                fis.close();
            }
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
}

If you think the article is a bit helpful to you, please search for " 程序猿编程" on WeChat to read it for the first time!

On the road of moving bricks, we work hard together and knock out our future with both hands!

Insert picture description here


Due to the limited level, this blog will inevitably have inadequacies. I hope you guys can give me your advice!

Guess you like

Origin blog.csdn.net/weixin_43570367/article/details/107451666