[java] 자바로 데이터를 압축해서 파일로 저장하기

자바를 사용하여 데이터를 압축하고 파일로 저장하는 방법에 대해 알아보겠습니다.

1. 압축 라이브러리 추가하기

자바에서 데이터를 압축하려면 java.util.zip 패키지의 ZipOutputStream 클래스를 사용합니다. 따라서 프로젝트에 해당 패키지를 추가해야 합니다.

Maven을 사용한다면 pom.xml 파일에 다음과 같은 의존성을 추가합니다:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.21</version>
</dependency>

Gradle을 사용한다면 build.gradle 파일의 dependencies 섹션에 다음과 같이 추가합니다:

dependencies {
    implementation 'org.apache.commons:commons-compress:1.21'
}

2. 데이터 압축하기

이제 압축할 데이터를 준비해야 합니다. 예를 들어, 문자열 데이터를 압축해보도록 하겠습니다:

String data = "압축할 데이터입니다.";

다음으로 압축할 데이터를 ZipOutputStream으로 래핑합니다:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try (ZipOutputStream zipOutputStream = new ZipOutputStream(byteArrayOutputStream)) {
    // 압축 진행
    zipOutputStream.putNextEntry(new ZipEntry("compressed_data.txt"));
    zipOutputStream.write(data.getBytes());
    zipOutputStream.closeEntry();
} catch (IOException e) {
    e.printStackTrace();
}

위 코드에서 ZipEntry는 압축 파일에 저장될 파일 경로 및 이름을 지정하는데 사용됩니다. 위의 예시에서는 “compressed_data.txt”로 설정했습니다.

압축된 데이터는 byteArrayOutputStream에 저장됩니다.

3. 파일로 저장하기

마지막으로 압축된 데이터를 파일로 저장합니다. 예를 들어, “compressed_data.zip”이라는 이름의 파일로 저장하고 싶다면 다음과 같이 저장할 수 있습니다:

try (FileOutputStream fileOutputStream = new FileOutputStream("compressed_data.zip")) {
    byteArrayOutputStream.writeTo(fileOutputStream);
} catch (IOException e) {
    e.printStackTrace();
}

위의 코드에서 “compressed_data.zip”은 저장될 파일의 경로와 이름을 나타냅니다.

이제 자바로 데이터를 압축하여 파일로 저장하는 방법을 알게 되었습니다. 이를 응용하여 다양한 데이터를 압축하고 파일로 저장할 수 있습니다.

참고 자료