实例展示使用Java压缩和解压缩7z文件的方法

所属分类: 软件编程 / java 阅读数: 45
收藏 0 赞 0 分享

压缩为7z文件
首先网络上对7z的压缩内容很少。
尤其是java调用进行压缩的是更少了。
一下是自己完成的一个压缩。
本人进行了测试是成功的。
将压缩的流写如磁盘一个压缩文件中。
然后使用7z的压缩软件进行打开解压。

7-zip的开源项目7-zip-JBinding项目地址(sourceforge)

不多说,调用7z源码进行压缩的方法如下。

public byte[] lzmaZip(String xml) throws IOException{ 
  BufferedInputStream inStream = new BufferedInputStream(new ByteArrayInputStream(xml.getBytes())); 
  ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
   
  boolean eos = true; 
    Encoder encoder = new Encoder(); 
    encoder.SetEndMarkerMode(eos); 
    encoder.WriteCoderProperties(bos); 
    long fileSize = xml.length(); 
    if (eos) 
      fileSize = -1; 
    for (int i = 0; i < 8; i++) 
      bos.write((int)(fileSize >>> (8 * i)) & 0xFF); 
    encoder.Code(inStream, bos, -1, -1, null); 
    return bos.toByteArray() ; 
} 

解压缩7z文件
利用7-zip的开源项目7-zip-JBinding来解压缩多种压缩文件,而不是调用外部命令(比如win下调用winrar)。

java自带的解压模块可解压缩的压缩类型有限。
代码示例

package core;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

import net.sf.sevenzipjbinding.ExtractOperationResult;
import net.sf.sevenzipjbinding.ISequentialOutStream;
import net.sf.sevenzipjbinding.ISevenZipInArchive;
import net.sf.sevenzipjbinding.SevenZip;
import net.sf.sevenzipjbinding.SevenZipException;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleInArchiveItem;
/**利用7zbinding*/
public class UnZip {


  void extractile(String filepath){
     RandomAccessFile randomAccessFile = null;
      ISevenZipInArchive inArchive = null;

      try {
        randomAccessFile = new RandomAccessFile(filepath, "r");
        inArchive = SevenZip.openInArchive(null, // autodetect archive type
            new RandomAccessFileInStream(randomAccessFile));

        // Getting simple interface of the archive inArchive
        ISimpleInArchive simpleInArchive = inArchive.getSimpleInterface();

        System.out.println("  Hash  |  Size  | Filename");
        System.out.println("----------+------------+---------");

        for (final ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
          final int[] hash = new int[] { 0 };
          if (!item.isFolder()) {
            ExtractOperationResult result;

            final long[] sizeArray = new long[1];
            result = item.extractSlow(new ISequentialOutStream() {
              public int write(byte[] data) throws SevenZipException {

                //Write to file
                FileOutputStream fos;
                try {
                  File file = new File(item.getPath());
                  //error occours below
//                 file.getParentFile().mkdirs();
                  fos = new FileOutputStream(file);
                  fos.write(data);
                  fos.close();

                } catch (FileNotFoundException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                } catch (IOException e) {
                  // TODO Auto-generated catch block
                  e.printStackTrace();
                }

                hash[0] ^= Arrays.hashCode(data); // Consume data
                sizeArray[0] += data.length;
                return data.length; // Return amount of consumed data
              }
            });
            if (result == ExtractOperationResult.OK) {
              System.out.println(String.format("%9X | %10s | %s", // 
                  hash[0], sizeArray[0], item.getPath()));
            } else {
              System.err.println("Error extracting item: " + result);
            }
          }
        }
      } catch (Exception e) {
        System.err.println("Error occurs: " + e);
        e.printStackTrace();
        System.exit(1);
      } finally {
        if (inArchive != null) {
          try {
            inArchive.close();
          } catch (SevenZipException e) {
            System.err.println("Error closing archive: " + e);
          }
        }
        if (randomAccessFile != null) {
          try {
            randomAccessFile.close();
          } catch (IOException e) {
            System.err.println("Error closing file: " + e);
          }
        }
      }
  }
}

调用的时候:

unzip=new UnZip();
unzip.extractile("a.7z");

会自动解压缩压缩包里的文件到当前目录下,当然可以更改设置,到特定的目录。代码简单明确。有问题可以到上面的sourceforge项目地址下的discuss搜索。

更多精彩内容其他人还在看

Springmvc restful配置遇到的小坑

本文是小编给大家带了的Springmvc restful配置遇到的小小坑,小编给大家带来了问题原因及解决办法,非常不错,具有参考借鉴价值,感兴趣的朋友一起看下吧
收藏 0 赞 0 分享

Java中的匿名内部类小结

java内部类分为: 成员内部类、静态嵌套类、方法内部类、匿名内部类。这篇文章主要介绍了Java中的匿名内部类的相关资料,需要的朋友可以参考下
收藏 0 赞 0 分享

Java的云打印Lodop

这篇文章主要介绍了Java的云打印Lodop 的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Java线程池框架核心代码解析

这篇文章主要针对Java线程池框架核心代码进行详细解析,分析Java线程池框架的实现ThreadPoolExecutor,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

Java 交换两个变量的数值实现方法

下面小编就为大家带来一篇Java 交换两个变量的数值实现方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

全面了解JAVA_BaseDAO数据处理类

下面小编就为大家带来一篇全面了解JAVA_BaseDAO数据处理类。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java、python、JavaScript以及jquery循环语句的区别

本篇文章主要介绍java、python、JavaScript以及jquery的循环语句的区别,这里整理了它们循环语句语法跟示例,以便大家阅读,更好的区分它们的不同
收藏 0 赞 0 分享

基于JDBC封装的BaseDao(实例代码)

下面小编就为大家带来一篇基于JDBC封装的BaseDao(实例代码)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

简单通用JDBC辅助类封装(实例)

下面小编就为大家带来一篇简单通用JDBC辅助类封装(实例)。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

浅谈java线程中生产者与消费者的问题

下面小编就为大家带来一篇浅谈java线程中生产者与消费者的问题。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享
查看更多