Java使用sevenzipjbind解压缩7z压缩包

来源:互联网 发布:安康软件开发公司 编辑:程序博客网 时间:2024/05/21 22:34


sevenzipjbind官网:  http://sevenzipjbind.sourceforge.net/

sevenzipjbind实际解压是通过调用动态库来实现的,所以对应不同平台需要用到不同的动态库。


动态库和源码以及jar包下载地址:http://sourceforge.net/projects/sevenzipjbind/files/7-Zip-JBinding/4.65-1.06rc-extr-only/

本文使用的是Windows平台来做演示。

下载sevenzipjbinding-4.65-1.06-rc-extr-only-AllWindows.zip

下载解压完以后将lib目录下面的sevenzipjbinding.jar以及sevenzipjbinding-AllWindows.jar拷入到项目当中。

实现代码:

首先定义一个提取文件的类

       /** * 压缩文件提取以及保存 */public class ExtractCallback implements IArchiveExtractCallback{private final Logger log = LoggerFactory.getLogger(ExtractCallback.class);        private int index;        private String packageName;        private ISevenZipInArchive inArchive;public ExtractCallback(ISevenZipInArchive inArchive, String packageName){this.inArchive = inArchive;this.packageName = packageName;}@Overridepublic void setCompleted(long arg0) throws SevenZipException {}@Overridepublic void setTotal(long arg0) throws SevenZipException {}@Overridepublic ISequentialOutStream getStream(int index, ExtractAskMode extractAskMode) throws SevenZipException {this.index = index;            final String path = (String) inArchive.getProperty(index, PropID.PATH);final boolean isFolder = (boolean)inArchive.getProperty(index, PropID.IS_FOLDER);            return new ISequentialOutStream() {                public int write(byte[] data) throws SevenZipException {                try {                if(ZipUtils.checkOnlyGetDir(path) && !isFolder){                        File file = buildUnPath(path);    ZipUtils.writeFiles(file, data);                }} catch (Exception e) {e.printStackTrace();}                    return data.length;                }            };}@Overridepublic void prepareOperation(ExtractAskMode arg0)throws SevenZipException {}@Overridepublic 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("失败!");                log.error(sb.toString());            }}}


使用SevenZip调取压缩包文件

        RandomAccessFile randomAccessFile = null;        ISevenZipInArchive inArchive = null;            //第一个参数是需要解压的压缩包路径,第二个参数参考JdkAPI文档的RandomAccessFile        randomAccessFile = new RandomAccessFile("d:\\366.zip", "r");        inArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));                int[] in = new int[inArchive.getNumberOfItems()];        for(int i=0;i<in.length;i++){            in[i] = i;        }        inArchive.extract(in, false, new ExtractCallback(inArchive, "366"));

以上只是涉及到简单的解压缩,更高级的使用请自行查阅官方doc。


0 0
原创粉丝点击