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

 更新时间:2015年11月10日 08:51:00   作者:FIND  
这篇文章主要介绍了实例展示使用Java压缩和解压缩7z文件的方法,用到了7-zip的开源项目7-zip-JBinding,需要的朋友可以参考下

压缩为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搜索。

相关文章

  • springboot多环境配置方案(不用5分钟)

    springboot多环境配置方案(不用5分钟)

    这篇文章主要介绍了springboot多环境配置方案(不用5分钟),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-01-01
  • Java观察者模式例子

    Java观察者模式例子

    这篇文章主要介绍了Java观察者模式例子的相关资料,需要的朋友可以参考下
    2015-12-12
  • 详解java中命令行模式的实现

    详解java中命令行模式的实现

    命令模式是一种行为设计模式,它允许您将请求封装为对象,以便您可以将其参数化、队列化、记录和撤销,本文主要为大家介绍一下java实现命令模式的示例代码,需要的可以参考下
    2023-09-09
  • idea启动多个SpringBoot服务实例的最优解决方法

    idea启动多个SpringBoot服务实例的最优解决方法

    启动SpringBoot项目其实就是启动Tomcat等服务容器,只要这个端口不同就能启动多个服务实例了,本文主要介绍了idea启动多个SpringBoot服务实例的最优解决方法,感兴趣的可以了解一下
    2024-05-05
  • Java策略模式实现简单购物车功能

    Java策略模式实现简单购物车功能

    这篇文章主要介绍了Java策略模式实现简单地购物车,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-08-08
  • java字符串比较获取字符串出现次数的示例

    java字符串比较获取字符串出现次数的示例

    java获取一个字符串在整个字符串出现的次数,下面写出我的思路和二个实现方法,大家参考使用吧
    2014-01-01
  • java代码实现mysql分表操作(用户行为记录)

    java代码实现mysql分表操作(用户行为记录)

    这篇文章主要介绍了java代码实现mysql分表操作(用户行为记录),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2021-02-02
  • java中串行流和并行流区别小结

    java中串行流和并行流区别小结

    串行流和并行流是两种处理流操作的方式,串行流适用于小数据量且简单的数据处理,并行流则适用于大规模数据处理和需要并行计算的场景,能够利用多线程并行处理,选择使用哪种流取决于数据量大小、处理复杂度和是否需要并行计算,下面就来具体介绍一下两者的区别
    2024-09-09
  • Java连接Oracle数据库实例解析

    Java连接Oracle数据库实例解析

    数据库的操作是当前系统开发必不可少的开发部分之一。接下来通过本文给大家介绍Java连接Oracle数据库实例解析,非常不错具有参考借鉴价值,感兴趣的朋友一起学习吧
    2016-06-06
  • @TableField注解之深入理解与应用方式

    @TableField注解之深入理解与应用方式

    在现代软件开发中,@TableField注解作为MyBatis-Plus中的一个重要特性,用于定义实体类字段与数据库表字段的映射关系,本文详细介绍了@TableField注解的使用场景、属性及其在实际开发中的应用,包括字段名称映射、非数据库字段标识、字段填充策略
    2024-10-10

最新评论