java decompress zip, rar file

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import com.github.junrar.Archive;
import com.github.junrar.rarfile.FileHeader;

/**
 *
 * @ClassName: FileCompress
 * @Description: TODO (here describes the role of this class in one sentence)
 * @author Zhou Yubo
 *@date April 11, 2017 at 9:30:11 AM
 *
 */
@SuppressWarnings("rawtypes")
public final class FileCompress{
	/**
     * zip decompression
     *
     * @param zipfile
     * File The file to be decompressed
     * @param descDir
     * String decompressed target directory
     */
    public static String unZipFiles(java.io.File zipfile, String descDir) {
    	InputStream in =null;
    	OutputStream out =null;
    	ZipFile zf=null;
    	File file=null;
    	String zipEntryName="";
        try {
        	descDir=descDir.replaceAll("\\/", "\\\\").replaceAll("\\.zip", "");
        	//jdk1.8 has no parameter Charset, suitable for 1.7
            zf = new ZipFile(zipfile,Charset.forName("GBK"));
            for (Enumeration entries = zf.entries(); entries
                    .hasMoreElements();) {
                ZipEntry entry = ((ZipEntry) entries.nextElement());
                zipEntryName = entry.getName();
                
                boolean ismkdir = false;  
                if(zipEntryName.lastIndexOf("/") != -1){ //Check if this file has a folder  
                   ismkdir = true;  
                }  
                zipEntryName = descDir+"\\" + zipEntryName;  
 
                if(entry.isDirectory()){ //If it is a folder, create it first  
                   file = new File(zipEntryName);  
                   file.mkdirs();  
                    continue;  
                }  
                file = new File(zipEntryName);  
                if(!file.exists()){ //If the directory is created first  
                   if(ismkdir){  
                   new File(zipEntryName.substring(0, zipEntryName.lastIndexOf("/"))).mkdirs(); //The directory is created first  
                   }  
                }  
                //file.createNewFile(); //Create a file
                
                in = zf.getInputStream(entry);
                File dstDiretory = new File(descDir);
                if (!dstDiretory.exists()) {// When the target directory does not exist, create the folder
                    dstDiretory.mkdirs();
                }
                out = new FileOutputStream(zipEntryName);
                byte[] buf1 = new byte[1024];
                int len;
                while ((len = in.read(buf1)) > 0) {
                    out.write(buf1, 0, len);
                }
                System.out.println("Decompression completed.");
            }
            return zipEntryName.replaceAll("/", "\\\\");
        } catch (IOException e) {
            e.printStackTrace ();
        }finally{
        	try {
	        	if(out!=null){
					out.close();
					out=null;
	        	}
	        	if(in!=null){
					in.close();
					in=null;
	        	}
	        	if(zf!=null){
	        		zf.close();
	        		zf=null;
	        	}
        	} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace ();
			}
        	System.gc();
        }
		return null;
    }

    /**
    * According to the original rar path, extract it to the specified folder.      
    * @param srcRarPath original rar path
    * @param dstDirectoryPath unzipped folder      
    */
    public static String unRarFile(String srcRarPath, String dstDirectoryPath) {
    	dstDirectoryPath=dstDirectoryPath.replaceAll("\\/", "\\\\").replaceAll("\\.rar", "");
    	//dstDirectoryPath=dstDirectoryPath.substring(0,dstDirectoryPath.lastIndexOf("\\"));
        if (!srcRarPath.toLowerCase().endsWith(".rar")) {
            System.out.println("Not a rar file!");
            return "";
        }
        File dstDiretory = new File(dstDirectoryPath);
        if (!dstDiretory.exists()) {// When the target directory does not exist, create the folder
            dstDiretory.mkdirs();
        }
        Archive a = null;
        FileOutputStream os=null;
        try {
            a = new Archive(new File(srcRarPath));
            if (a != null) {
                a.getMainHeader().print(); // Print file information.
                FileHeader fh = a.nextFileHeader();
                while (fh != null) {
                    if (fh.isDirectory()) { // folder
                        File fol = new File(dstDirectoryPath + File.separator
                                + fh.getFileNameString());
                        fol.mkdirs();
                    } else { // file
                        File out = new File(dstDirectoryPath + File.separator
                                + fh.getFileNameString().trim());
                        //System.out.println(out.getAbsolutePath());
                        try {// The reason why try is written like this is that if there is an exception here, it will not affect the continued decompression.
                            if (!out.exists()) {
                                if (!out.getParentFile().exists()) {// The relative path may be multi-level, and a parent directory may need to be created.
                                    out.getParentFile().mkdirs();
                                }
                                out.createNewFile();
                            }
                            os = new FileOutputStream(out);
                            a.extractFile(fh, os);
                        } catch (Exception ex) {
                            ex.printStackTrace();
                        }finally{
                        	if(os!=null){
                        		os.close();
                        		os=null;
                        	}
                        }
                    }
                    fh = a.nextFileHeader();
                }
            }
            return dstDirectoryPath;
        } catch (Exception e) {
            e.printStackTrace ();
        }finally{
        	if(a!=null){
        		try {
					a.close();
					a=null;
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace ();
				}
        	}
        }
        return "";
    }
}
The decompression of RAR needs to import the package junrar-0.7.jar

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325594993&siteId=291194637