[java] 자바에서 7zip 파일을 압축 및 해제하는 방법

안녕하세요! 오늘은 자바에서 7zip 파일을 압축하고 해제하는 방법에 대해 알아보겠습니다. 7zip은 오픈 소스 압축 프로그램으로, 다양한 압축 형식을 지원하며 뛰어난 압축률과 보안 기능을 제공합니다.

1. 7zip 라이브러리 추가

7zip 파일 압축 및 해제를 위해 SevenZipJBinding 라이브러리를 사용합니다. 이 라이브러리는 자바에서 7zip을 편리하게 사용할 수 있도록 도와줍니다. 다음과 같이 Maven을 사용하여 라이브러리를 추가할 수 있습니다.

<dependency>
  <groupId>net.sf.sevenzipjbinding</groupId>
  <artifactId>sevenzipjbinding</artifactId>
  <version>16.02-1.09</version>
</dependency>

2. 7zip 파일 압축하기

import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;
import net.sf.sevenzipjbinding.simple.ISimpleOutArchive;
import net.sf.sevenzipjbinding.simple.OutArchiveFormat;

import java.io.*;

public class SevenZipCompressionExample {

    public static void main(String[] args) {

        File fileToCompress = new File("path/to/file");  // 압축할 파일 경로
        File compressedFile = new File("path/to/compressed/file.7z");  // 압축된 파일 경로

        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(fileToCompress, "r");

            IInArchive readArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));

            ISimpleOutArchive simpleOutArchive = readArchive.getSimpleInterface().getArchiveFormat().equals(OutArchiveFormat.SEVEN_ZIP)
                    ? readArchive.getSimpleInterface()
                    : SevenZip.openOutArchive(OutArchiveFormat.SEVEN_ZIP);

            try (OutputStream outputStream = new FileOutputStream(compressedFile)) {
                simpleOutArchive.createArchive(new OutputStreamSequentialOutStream(outputStream), fileToCompress.listFiles());
            }

            readArchive.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

위의 코드에서 fileToCompress 변수는 압축할 파일의 경로를, compressedFile 변수는 압축된 파일의 경로를 각각 지정해주세요. 압축된 파일은 .7z 형식으로 저장됩니다.

3. 7zip 파일 해제하기

import net.sf.sevenzipjbinding.*;
import net.sf.sevenzipjbinding.impl.RandomAccessFileInStream;
import net.sf.sevenzipjbinding.simple.ISimpleInArchive;

import java.io.*;

public class SevenZipExtractionExample {

    public static void main(String[] args) {

        File compressedFile = new File("path/to/compressed/file.7z");  // 압축 파일 경로
        File destinationFolder = new File("path/to/destination/folder");  // 해제할 폴더 경로

        try {
            RandomAccessFile randomAccessFile = new RandomAccessFile(compressedFile, "r");

            IInArchive readArchive = SevenZip.openInArchive(null, new RandomAccessFileInStream(randomAccessFile));

            ISimpleInArchive simpleInArchive = readArchive.getSimpleInterface();

            for (ISimpleInArchiveItem item : simpleInArchive.getArchiveItems()) {
                if (!item.isFolder()) {
                    File outputFile = new File(destinationFolder, item.getPath());

                    if (!outputFile.getParentFile().exists()) {
                        outputFile.getParentFile().mkdirs();
                    }

                    try (OutputStream outputStream = new FileOutputStream(outputFile)) {
                        item.extractSlow(new OutputStreamSequentialOutStream(outputStream));
                    }
                }
            }

            readArchive.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

위의 코드에서 compressedFile 변수는 해제할 압축 파일의 경로를, destinationFolder 변수는 해제할 폴더의 경로를 각각 지정해주세요. 실제 파일은 원본 압축 파일의 구조를 유지한 채 압축 해제됩니다.

이제 자바에서 7zip 파일을 압축하고 해제하는 방법에 대해 알게 되었습니다. 문제가 발생하면 해당 라이브러리의 문서나 예제 코드를 참조하는 것도 도움이 될 것입니다.

참고 자료: