java 解压rar文件

https://github.com/ShenZhenSogaaTech/sogaa-web/blob/b1ef0d8bd582bbf4e0e4fb7ad0e39657f2b307d0/src/main/java/com/sogaa/system/utils/ZipUtils.java

 

 

 

 maven依赖关系

 

		
		
			com.github.junrar
			junrar
			0.7
		

 

 

import com.github.junrar.Archive;
import com.github.junrar.exception.RarException;
import com.github.junrar.rarfile.FileHeader;
import org.junit.Test;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.List;

/**
 * Created by on 2017/2/28.
 */
public class RarTest {

    /**
     * @param rarFileName rar file name
     * @param outFilePath output file path
     * @return success Or Failed
     * @throws Exception
     * @author zhuss
     */
    public static boolean unrar(String rarFileName, String outFilePath) throws Exception {

        boolean flag = false;
        try {
            Archive archive = new Archive(new File(rarFileName));
            if (archive == null) {
                throw new FileNotFoundException(rarFileName + " NOT FOUND!");
            }
            if (archive.isEncrypted()) {
                throw new Exception(rarFileName + " IS ENCRYPTED!");
            }
            List files = archive.getFileHeaders();
            for (FileHeader fh : files) {
                if (fh.isEncrypted()) {
                    throw new Exception(rarFileName + " IS ENCRYPTED!");
                }
                String fileName = fh.getFileNameString();
                if (fileName != null && fileName.trim().length() > 0) {
                    String saveFileName = outFilePath + "\\" + fileName;
                    File saveFile = new File(saveFileName);
                    File parent = saveFile.getParentFile();
                    if (!parent.exists()) {
                        parent.mkdirs();
                    }
                    if (!saveFile.exists()) {
                        saveFile.createNewFile();
                    }
                    FileOutputStream fos = new FileOutputStream(saveFile);
                    try {
                        archive.extractFile(fh, fos);
                        fos.flush();
                        fos.close();
                    } catch (RarException e) {
                        if (e.getType().equals(RarException.RarExceptionType.notImplementedYet)) {
                        }
                    } finally {
                    }
                }
            }
            flag = true;
        } catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        return flag;
    }

    @Test
    public void unrar() throws Exception {

        RarTest.unrar("/install/putty.rar", "/test");
    }

}

 

 

你可能感兴趣的:(java 解压rar文件)