[java] ZIP 압축 방법을 사용하여 파일 압축하기

먼저, ZipOutputStream을 사용하여 ZIP 파일을 생성하고, 압축할 파일들을 추가합니다.

다음은 압축기능이 포함된 클래스의 예제입니다.

import java.io.*;
import java.util.zip.*;

public class ZipExample {
    public static void main(String[] args) {
        byte[] buffer = new byte[1024];

        try {
            File fileToZip = new File("file.txt");
            FileOutputStream fos = new FileOutputStream("compressed.zip");
            ZipOutputStream zos = new ZipOutputStream(fos);
            ZipEntry zipEntry = new ZipEntry(fileToZip.getName());
            zos.putNextEntry(zipEntry);

            FileInputStream fis = new FileInputStream(fileToZip);
            int length;
            while ((length = fis.read(buffer)) > 0) {
                zos.write(buffer, 0, length);
            }
            fis.close();
            zos.closeEntry();

            zos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

이 예제는 “file.txt” 파일을 “compressed.zip”에 압축하는 내용을 담고 있습니다. 코드 실행 후 “compressed.zip” 파일은 “file.txt” 파일을 포함하고 있을 것입니다.

더 복잡한 압축 요구사항이 있다면, ZipOutputStream 클래스의 다양한 메소드를 사용하여 원하는 내용으로 수정할 수 있습니다.

추가적인 정보는 Oracle Java Documentation에서 확인할 수 있습니다.