java Compressed File and Download Example Explanation

  • 2021-08-21 20:29:42
  • OfStack

When we sort out some data that need to be used, we will find that the memory of the file occupies a lot, but it is not very convenient to download or store it. At this time, we will think of turning the file into zip format, that is, compressing it. Before officially starting to compress and download files, we can first understand the format of zip, and then share the specific methods for everyone.

1. ZIP file format

[local file header + file data + data descriptor]{1,n} + central directory + end of central directory record
I.e.
[File Header + File Data + Data Descriptor] {n Repeatable Here} + Core Directory + Directory End Identifier When there are multiple files in the compressed package, there will be multiple [File Header + File Data + Data Descriptor]

2. Compression and download steps

(1) Prepare before creating a compressed package


// Define the path where the compressed package exists on the server 
String path = request.getSession().getServletContext().getRealPath("/WEB-INF/fileTemp");
// Create path 
File FilePath = new File(path + "/file");
if (!FilePath.exists()) {
FilePath.mkdir();
}
String path = FilePath.getPath() + "/";
// Define the name of the exported compressed package 
String title =" Ask price compression package ";
// Compressed packet format 
String fileNamezip = title + ".zip";
String zipPath = path + fileNamezip;
// Create 1 A ZIP Output the stream and instantiate the buffer region 
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(zipPath)));
// Format encoding ( Solve linux Garbled code appears )
out.setEncoding("gbk");
// Defining an array of bytes 
byte data[] = new byte[2048];
// Get file records ( Get file record code omission )
List FileList = . . . ;
if (!FileList.isEmpty()) {
ExportUtil util = new ExportUtil(title,title,
request, response, FilePath.getPath());
}

(2) Delete the data before the compressed package and create the compressed package


util.startZip(FilePath.getPath());

(3) Loop to put the files to be compressed into the compressed package


for (int i = 0; i < FileList.size(); i++) {
fileVo fileVo=FileList.get(i);
export(fileVo,request,response,title,FilePath.getPath(),fileName);
}
------
public void export(fileVo fileVo, HttpServletRequest request,
HttpServletResponse response, String title,String path, String fileName) {
FileOutputStream fileOutputStream = null;
try {
File dirFile = null; 
int i = fileVo.getName().lastIndexOf(".");
    if(i!=-1){// File type exists 
     fileName1 = fileName1 + "." + (fileVo.getName()).substring(i+1);
    }
boolean bFile = false;
String mkdirName = path + File.separatorChar + title;
dirFile = new File(mkdirName);
if(!dirFile.exists()) {
dirFile.getParentFile().mkdirs();
}
if (dirFile.isDirectory()) {
path = mkdirName + File.separatorChar + fileName1;
} else {
bFile = dirFile.mkdirs();
}
if (bFile) {
path = mkdirName + File.separatorChar + fileName1;
} 
fileOutputStream = new FileOutputStream(path.replace("*", "")); 
String fileName = URLEncoder.encode(fileName1, "UTF-8");
if (fileName.length() > 110) {
fileName = new String(fileName1.getBytes("gb2312"), "ISO8859-1");
}
response.setHeader("Connection", "close");
response.setHeader("Content-Type", "application/octet-stream");
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition", "attachment; filename=\""
+ Utf8Util.toUtf8String(fileName) + "\"");
// Read the file stream output to another 1 Position 
fileVo.getFileIo(fileOutputStream);
fileOutputStream.close(); 
} catch (Exception e) {
logger.error(" Exception: The reason is as follows "+e.getMessage(), e);
} finally {
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (IOException e1) {
// TODO Auto-generated catch block
logger.error(" Exception: The reason is as follows "+e1.getMessage(), e1);
}
}
}

(4) After compression, close the output stream.


util.entdZip(FilePath.getPath());

java Generate Compressed File Sample Code Extension


import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;
/** 
 * @project: Test 
 * @author chenssy
 * @date 2013-7-28 
 * @Description:  File compression tool class 
 *                    The file will be specified / Folder is compressed into zip , rar Zip file 
 */
public class CompressedFileUtil {
    /**
     *  Default constructor 
     */
    public CompressedFileUtil(){

    }
    /**
     * @desc  Will the source file / Folder generates a compressed file in the specified format , Format zip
     * @param resourePath  Source file / Folder 
     * @param targetPath   Destination zip file save path 
     * @return void
     * @throws Exception 
     */
    public void compressedFile(String resourcesPath,String targetPath) throws Exception{
        File resourcesFile = new File(resourcesPath);     // Source file 
        File targetFile = new File(targetPath);           // Purpose 
        // If the destination path does not exist, create a new 
        if(!targetFile.exists()){     
            targetFile.mkdirs();  
        }

        String targetName = resourcesFile.getName()+".zip";   // Destination zip file name 
        FileOutputStream outputStream = new FileOutputStream(targetPath+"\\"+targetName);
        ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(outputStream));

        createCompressedFile(out, resourcesFile, "");

        out.close();  
    }

    /**
     * @desc  Generate a compressed file. 
     *                   If it is a folder, recursion is used, file traversal is performed, and compression is performed 
     *        If it is a file, compress it directly 
     * @param out   Output stream 
     * @param file   Object file 
     * @return void
     * @throws Exception 
     */
    public void createCompressedFile(ZipOutputStream out,File file,String dir) throws Exception{
        // If the current folder is a folder, proceed to 1 Step processing 
        if(file.isDirectory()){
            // Get file list information 
            File[] files = file.listFiles();
            // Add a folder to the following 1 Level packaging directory 
            out.putNextEntry(new ZipEntry(dir+"/"));

            dir = dir.length() == 0 ? "" : dir +"/";

            // Loop to pack the files in the folder 
            for(int i = 0 ; i < files.length ; i++){
                createCompressedFile(out, files[i], dir + files[i].getName());         // Recursive processing 
            }
        }
        else{   // The current one is a file, which is packaged and processed 
            // File input stream 
            FileInputStream fis = new FileInputStream(file);

            out.putNextEntry(new ZipEntry(dir));
            // Perform a write operation 
            int j =  0;
            byte[] buffer = new byte[1024];
            while((j = fis.read(buffer)) > 0){
                out.write(buffer,0,j);
            }
            // Close the input stream 
            fis.close();
        }
    }

    public static void main(String[] args){
        CompressedFileUtil compressedFileUtil = new CompressedFileUtil();

        try {
            compressedFileUtil.compressedFile("G:\\zip", "F:\\zip");
            System.out.println(" The zip file has been generated ...");
        } catch (Exception e) {
            System.out.println(" Compressed file generation failed ...");
            e.printStackTrace();
        }
    }
}

Related articles: