java upload zip file and extract it

Keywords: Spring Apache

Recently, I met such a demand: transfer a compression package to the background, decompress and read the files in the background after saving, and now I am learning to do it. Make a record here

File upload

There are many ways to upload files. Here I recommend one that I feel is very good to use. Here is the code:

 @PostMapping(value = "/import", headers = "content-type=multipart/*")

    public R importSqlLite(@RequestParam("file") MultipartFile file) {
     String path = "C:/Users/aaa/Desktop/New folder/";

            File newFile = new File(path + file.getOriginalFilename());
            //Write files directly through CommonsMultipartFile (note this time)

            file.transferTo(newFile);
    }

File decompression

After referring to many blogs, we found two ways to decompress. One is to use the package org.apache.tools.zip.ZipFile, and the other is the spring boot's own net.lingala.zip4j.core.ZipFile. Because it uses the second type of spring boot project, the code is presented as follows:

 //Decompression path
    private String dest = "C:\\Users\\aaa\\Desktop\\New folder";
    //The path to save the extracted image
    private String picPath = "C:/Users/aaa/Desktop/New folder/pic";


    public String Uncompress(String source) {
        List<String> picPaths = new ArrayList<>();
        try {
            File zipFile = new File(source);
            ZipFile zFile = new ZipFile(zipFile);// First, create a. zip file that points to the disk.

            zFile.setFileNameCharset("GBK");

            File destDir = new File(dest);// Decompress directory 
            zFile.extractAll(dest);// Extract the file to the unzip directory
              if (zFile.isEncrypted()) {   
                  zFile.setPassword(password.toCharArray());  // Set password   
              }
              zFile.extractAll(dest);      // Extract the file to the unzip directory (unzip)   
     
             List<net.lingala.zip4j.model.FileHeader > headerList = zFile.getFileHeaders(); 
              List<File> extractedFileList= newArrayList<File>(); 
              for(FileHeader fileHeader : headerList) { 
                  if (!fileHeader.isDirectory()) { 
                      extractedFileList.add(new File(destDir,fileHeader.getFileName())); 
                  } 
              } 
              File [] extractedFiles = new File[extractedFileList.size()]; 
             extractedFileList.toArray(extractedFiles); 
              for(File f:extractedFileList){
                System.out.println(f.getAbsolutePath()+"....");
              }

      }catch(ZipException e) {
      } 

Posted by ohjay on Thu, 24 Oct 2019 07:08:06 -0700