[java] 압축된 데이터를 자바로 읽어들여 다른 파일로 저장하는 방법

압축된 데이터를 자바로 읽어들여 다른 파일로 저장하는 방법에 대해 알아보겠습니다.

1. Zip 파일 열기

먼저, 압축된 데이터가 포함된 Zip 파일을 열어야 합니다. 이를 위해 java.util.zip.ZipInputStream 클래스를 사용할 수 있습니다. 아래는 Zip 파일을 열고 압축된 파일을 읽는 코드 예시입니다.

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipReader {
    public static void main(String[] args) {
        try {
            // Zip 파일 경로
            String zipFilePath = "/path/to/zip/file.zip";
            
            // ZipInputStream 생성
            ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath));
            
            ZipEntry entry;
            byte[] buffer = new byte[1024];
            
            // 압축된 파일 읽기
            while ((entry = zipInputStream.getNextEntry()) != null) {
                // 압축된 파일명
                String entryName = entry.getName();
                
                // 새로운 파일 생성
                FileOutputStream fileOutputStream = new FileOutputStream("/path/to/output/directory/" + entryName);
                
                int length;
                
                // 압축된 파일 내용을 읽어서 새로운 파일로 저장
                while ((length = zipInputStream.read(buffer)) > 0) {
                    fileOutputStream.write(buffer, 0, length);
                }
                
                fileOutputStream.close();
                zipInputStream.closeEntry();
            }
            
            zipInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

2. 실행 및 결과

위의 코드를 실행하면, 지정된 Zip 파일을 열고 압축된 파일을 읽어서 지정된 출력 디렉터리에 복원합니다.

압축된 데이터를 읽어들여 다른 파일로 저장하는 방법에 대한 예시입니다. Zip 파일 이외에도 다른 압축 형식에 대해서도 비슷한 방법으로 처리할 수 있습니다.

참고 자료