▼ Backend/자바 (JAVA)

JAVA | 압축(zip)파일 해제하기

Valar 2022. 6. 7. 16:58
반응형

 java.util.zip

자바에서 기본적으로 제공하는 패키지로 압축 파일(zip)의 압축 및 해제를 할 수 있다.

구성환경

Windows 10, IntelliJ IDEA 2022.1.2, Java 1.8

 

압축 파일 해제 예제
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class CompressUtil {

    public void unCompressZip() throws Exception {
        // 압축(zip) 파일의 경로
        String zipFolder = "C:\\Users\\NB061\\Downloads\\";

        // 경로/demo.zip 이름으로된 파일에 대한 파일 객체 생성
        File zipFile = new File(zipFolder, "demo.zip");

        // 해당 파일에 대한 연결을 열어 FileInputStream -> BufferedInputStream 생성
        try (BufferedInputStream in = new BufferedInputStream(new FileInputStream(zipFile))) {
            // BufferedInputStream에 대한 ZipInputStream 생성
            try (ZipInputStream zipInputStream = new ZipInputStream(in)) {
                ZipEntry zipEntry = null;
                // 다음 ZIP 파일 항목을 읽고 항목 데이터의 시작 부분에 스트림을 배치, 항목이 null이 아니면 while
                while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                    int length = 0;
                    try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(zipFolder + zipEntry.getName()))) {
                        // 생성된 빈 파일에 실제 내용을 write
                        while ((length = zipInputStream.read()) != -1) {
                            out.write(length);
                        }
                        // 현재 ZIP 항목을 닫고 다음 항목을 읽을 수 있도록 스트림을 배치
                        zipInputStream.closeEntry();
                    }
                }
            }
        }
    }
}

 

테스트

압축 해제 할 zip 파일

 

압축 해제 후 파일목록

 

Download

CompressUtil.java
0.00MB

 

압축 하기 예제

Reference

반응형