The example shows how to compress and uncompress 7z files using Java

  • 2020-04-01 04:20:54
  • OfStack

Compress to 7z file
First of all, there is very little compressed content for 7z on the network.
In particular, Java calls compress less.
The following is a compression done by itself.
I conducted the test and it was successful.
To write a compressed stream as to disk in a compressed file.
Then use 7z compression software to open the decompression.

7 - the open source project 7 zip zip - JBinding (link: http://sourceforge.net/projects/sevenzipjbind/)

Without further ado, the method of calling 7z source code to be compressed is as follows.


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() ; 
} 

Unzip the 7z file
Use the 7-zip open source project 7-zip-jbinding to unzip a variety of compressed files instead of calling external commands (such as the win call to winrar).

Java's native decompression module has a limited number of decompression types.
Code sample


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;

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);
          }
        }
      }
  }
}

When invoked:


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

Will automatically unzip the files in the zip package to the current directory, of course, you can change the Settings to a specific directory. The code is simple and unambiguous. You can go to the discuss search at the sourceforge project address above for questions.


Related articles: