7-zip 解压

7-zip 解压

1、引入依赖文件

sevenzipjbinding.jar
sevenzipjbinding-Allwindows.jar
<!-- https://mvnrepository.com/artifact/net.sf.sevenzipjbinding/sevenzipjbinding -->
<dependency>
    <groupId>net.sf.sevenzipjbinding</groupId>
    <artifactId>sevenzipjbinding</artifactId>
    <version>9.20-2.00beta</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sf.sevenzipjbinding/sevenzipjbinding-all-windows -->
<dependency>
    <groupId>net.sf.sevenzipjbinding</groupId>
    <artifactId>sevenzipjbinding-all-windows</artifactId>
    <version>9.20-2.00beta</version>
</dependency>

  

2、创建IInArchive

public class SevenZipServer {
Logger logger = Logger.getLogger(SevenZipServer.class);

/**
*This method USES zip7 to decompress the file, need the parameter decompression file, unzip the path
* Unpack The supported format is zip, rar,tar
* @param zipFile
* @param unpackPath
*/
public boolean extractZIP7(String zipFile,String unpackPath ){
IInArchive archive = null;
RandomAccessFile randomAccessFile = null;
boolean success = false;
try {
randomAccessFile = new RandomAccessFile(zipFile, "rw");
archive = SevenZip.openInArchive(null,
new RandomAccessFileInStream(
randomAccessFile));
int[] in = new int[archive.getNumberOfItems()];
for(int i=0;i<in.length;i++){
in[i] = i;
}
archive.extract(in, false, new Zip7ExtractCallback(archive, unpackPath));
success = true;
}catch (FileNotFoundException e){
logger.error(zipFile+"-FileNotFoundException occurs: ");
e.printStackTrace();
}catch (SevenZipException e){
logger.error("SevenZipException occurs: ");
e.printStackTrace();
}finally {
try {
archive.close();
randomAccessFile.close();
}catch (IOException e){

}
}
return success;
}

}

3、创建提取文件实现类

public class ExtractCallback implements IArchiveExtractCallback {
    private int index;
    private String packageName;
    private String unzipPath;
    private IInArchive inArchive;

    public ExtractCallback(IInArchive inArchive, String packageName,String unzipPath) {
        this.inArchive = inArchive;
        this.packageName = packageName;
        this.unzipPath = unzipPath;
    }

    public ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {
        this.index = index;
        final String path = (String) inArchive.getProperty(index, PropID.PATH);
        System.out.println("path === >"+ path);
        final boolean isFolder = (Boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
        return new ISequentialOutStream() {
            public int write(byte[] data) throws SevenZipException {
                try {
                    if (!isFolder) {
                        String path1 = unzipPath+path;

                        File file = buildUnPath(path1);
                        writeFiles(file, data);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return data.length;
            }
        };
    }

    public void prepareOperation(ExtractAskMode arg0) throws SevenZipException {
    }

    public void setOperationResult(ExtractOperationResult extractOperationResult) throws SevenZipException {
        String path = (String) inArchive.getProperty(index, PropID.PATH);
        boolean isFolder = (Boolean) inArchive.getProperty(index, PropID.IS_FOLDER);
        /*if (ZipUtils.checkOnlyGetDir(path) && !isFolder) {
            if (extractOperationResult != ExtractOperationResult.OK) {
                StringBuilder sb = new StringBuilder();
                sb.append("解压").append(packageName).append("包的").append(path).append("文件");
                sb.append("失败!");
            }
        }*/
        if (!isFolder) {
            if (extractOperationResult != ExtractOperationResult.OK) {
                StringBuilder sb = new StringBuilder();
                sb.append("解压").append(packageName).append("包的").append(path).append("文件");
                sb.append("失败!");
            }
        }

    }

    public void setTotal(long l) throws SevenZipException {

    }

    public void setCompleted(long l) throws SevenZipException {

    }


}

  4、工具类

public class ZipUtils {
    public static FileOutputStream fileOutputStream = null;
    public static void writeFiles(File file,byte[] data){
        try {
            fileOutputStream = new FileOutputStream(file);
            fileOutputStream.write(data);
            fileOutputStream.close();

        }catch (FileNotFoundException e){
            System.out.println(file.getName()+"没有找到该文件或目录");
        }catch (IOException e){
            System.out.println(file.getName()+"IO异常");
        }
    }
    public static File buildUnPath(String path){
        String[] pathDir = path.split("\\\\");
        if (pathDir.length != 1){
            new File(path.substring(0,path.lastIndexOf("\\"))).mkdirs();
        }
        File file = new File(path);
        return file;
    }

    public static byte[] getBytes(String filePath){
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }
}

5、调用方式:

 1 public class Main {
 2     public static void main(String[] args) throws Exception{
 3         //解压文件
 4         String path = ""; // 压缩文件
 5         String unzipPath = ""; //解压目录
 6         SevenZipServer server = new SevenZipServer();
 7        /* System.out.println("---------------开始解压---------------------");
 8         server.unZip(path,unzipPath);
 9         System.out.println("---------------解压完成---------------------");*/
10 
11         System.out.println("---------------开始压缩---------------------");
12         server.zip(path,unzipPath, ArchiveFormat.ZIP);
13         System.out.println("---------------压缩完成---------------------");
14     }
15 }
View Code

  github 地址:https://github.com/1182632074/SevenZIP

posted @ 2017-05-05 09:11  wangshunyao  阅读(2063)  评论(0编辑  收藏  举报