예를 들어 Java를 사용하여 7z 파일을 압축 및 압축 해제하는 방법을 보여 줍니다.

5519 단어 Java압축
7z 파일로 압축
우선 인터넷에서 7z에 대한 압축 내용이 매우 적다.
특히 자바 호출은 압축을 하는 것이 더 적다.
한 번은 스스로 완성한 압축이다.
본인이 테스트를 진행한 것은 성공적이었다.
압축된 흐름을 디스크의 압축 파일처럼 쓰십시오.
그리고 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로 검색할 수 있습니다.

좋은 웹페이지 즐겨찾기