[java] 자바에서 압축 파일에 접근해서 파일을 읽거나 쓰는 방법

자바에서는 java.util.zip 패키지를 사용하여 압축 파일에 접근하고 파일을 읽거나 쓸 수 있습니다. 이 패키지는 압축 파일을 읽기 위한 ZipInputStream 클래스와 압축 파일에 쓰기 위한 ZipOutputStream 클래스를 제공합니다.

압축 파일에서 파일 읽기

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

public class ZipFileReader {

    public static void main(String[] args) {
        String zipFilePath = "path/to/your/archive.zip";

        try (ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFilePath))) {
            ZipEntry zipEntry;
            while ((zipEntry = zipInputStream.getNextEntry()) != null) {
                if (!zipEntry.isDirectory()) {
                    String fileName = zipEntry.getName();
                    // 파일 읽기 작업 수행
                    // ...
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 ZipInputStream을 사용하여 압축 파일에서 파일을 읽어오고 있습니다. getNextEntry 메서드를 호출하여 다음 엔트리를 가져올 수 있습니다. 각 엔트리는 ZipEntry 객체로 나타내며, isDirectory 메서드를 통해 디렉토리인지 확인할 수 있습니다. 파일인 경우, getName 메서드를 통해 파일 이름을 가져올 수 있습니다.

압축 파일에 파일 쓰기

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipFileWriter {

    public static void main(String[] args) {
        String zipFilePath = "path/to/your/archive.zip";
        String fileToCompress = "path/to/your/file.txt";

        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(zipFilePath))) {
            ZipEntry zipEntry = new ZipEntry("file.txt");
            zipOutputStream.putNextEntry(zipEntry);

            byte[] buffer = new byte[1024];
            int length;
            try (FileInputStream fileInputStream = new FileInputStream(fileToCompress)) {
                while ((length = fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, length);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

위의 예제에서는 ZipOutputStream을 사용하여 압축 파일에 파일을 쓰고 있습니다. putNextEntry 메서드를 호출하여 다음 엔트리를 생성합니다. 그리고 파일을 읽어와서 write 메서드를 통해 압축 파일에 기록합니다. 반복적으로 read 메서드를 호출하여 파일을 청크 단위로 읽고 기록합니다.

압축 파일에 암호를 설정하거나 다른 압축 형식을 사용하는 등의 작업도 java.util.zip 패키지를 통해 수행할 수 있습니다. 자세한 내용은 Java 공식 문서를 참조하시기 바랍니다.