Java compressed files and folders

Posted by [JayZ] on Fri, 06 Dec 2019 21:05:32 +0100

Not updated for a long time
Ten thousand words are omitted here. Hu Hansan is back again!!!! get down to business...

This time, the main function is to achieve: according to the incoming path, compress files and folders, for example, compress files from path A to directory B, including empty folders. Not much nonsense, directly on the code: (this is A tool class, idea pro test available!!)

                        import java.util.zip.ZipFile;
                        import  org.apache.tools.zip.*;
                        import java.io.*;

                    /*********  1.Compress files and folders*******/   
       public  static void zipFile(ZipOutputStream zipOutputStream, File file, String parentFileName) {
       FileInputStream in = null;
        try {
        org.apache.tools.zip.ZipEntry zipEntry = new org.apache.tools.zip.ZipEntry(parentFileName);
        //  ZipEntry zipEntry = new ZipEntry(file.getName());
        zipEntry.setTime(file.lastModified());
        zipOutputStream.putNextEntry(zipEntry);
        in = new FileInputStream(file);
        int len;
        byte[] buf = new byte[8 * 1024];
        while ((len = in.read(buf)) != -1) {
            zipOutputStream.write(buf, 0, len);
        }
        zipOutputStream.closeEntry();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }catch (Exception e){
        e.printStackTrace();
    }finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

    /**
 * 2.Recursively compressed directory structure
 *
 * @param zipOutputStream
 * @param file
 * @param parentFileName
 */
public  static void directory(org.apache.tools.zip.ZipOutputStream zipOutputStream, File file, String parentFileName) {
    File[] files = file.listFiles();
    String parentFileNameTemp = null;
    for (File fileTemp : files) {
        String   fileTempName = fileTemp.getName().substring(fileTemp.getName().indexOf(".") + 1);
        if(fileTempName.equals("zip")){
            fileTemp.delete();
            continue;
        }
        parentFileNameTemp = com.dy.core.sims.utils.StringUtils.isEmpty(parentFileName) ? fileTemp.getName() : parentFileName + "/" + fileTemp.getName();
        if (fileTemp.isDirectory()) {
            directory(zipOutputStream, fileTemp, parentFileNameTemp);
        }else {
            zipFile(zipOutputStream, fileTemp, parentFileNameTemp);
        }
    }

    if(files.length==0){
        try{
            zipOutputStream.putNextEntry(new ZipEntry (getPath(file)+File.separator));
        }catch (Exception e){
            e.printStackTrace();
            }

             }
          }

           //3. Obtain the relative path of the file in the compressed package
      public  static  String getPath (File f) {
    String str1 = f.getAbsolutePath();
    int n1= str1.length();
    String str2 = f.getAbsolutePath();
    int n2= str2.length();
    String str3 = f.getName();
    int n3= str3.length();
    String str = str2.substring(n1-n3, n2);
    return str;
       }

                 /**
 * 4.Compressed file directory
 *
 * @param source Source file directory (single file and multi-level directory)
 * @param destit Target directory
 */
public static Boolean  compressFiles(String source, String destit) {
    //Determine whether the path exists
    String   de=destit.substring(0, destit.lastIndexOf("//")+2);
    File  targetFile=new File(source);
    File  fileTarget=new File(de);
    if(!targetFile.exists() || !fileTarget.exists()){
        return false;
    }
    File file = new File(source);
    org.apache.tools.zip.ZipOutputStream zipOutputStream = null;
    FileOutputStream fileOutputStream = null;
    try {
        fileOutputStream = new FileOutputStream(destit);
        zipOutputStream = new ZipOutputStream(fileOutputStream);
        if (file.isDirectory()) {
            directory(zipOutputStream, file, "");
        } else {
            zipFile(zipOutputStream, file, "");
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        try {
            zipOutputStream.close();
            fileOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return  true;
      }

                /**
 * test
 *
 * @param args
 */
public static void main(String[] args) {

    try{

       Boolean  flag=compressFiles("D://Excel//","D://Excel//aa.zip");
        System.out.println(flag);
    }catch (Exception e){
        e.printStackTrace();
         }
    }

All the code is on this. The jar package to be used is org.apache.tools.zip. You can refer to it if you need it. If it's not correct, I hope you will not hesitate to teach me

Topics: Web Development Apache Java Excel