[java] 자바에서 압축 파일 내 특정 파일을 웹에서 다운로드하기

이 포스트에서는 자바를 사용하여 압축 파일(.zip, .tar 등) 내의 특정 파일을 웹에서 다운로드하는 방법에 대해 알아보겠습니다.

1. Apache Commons IO 라이브러리 추가

먼저, Apache Commons IO 라이브러리를 프로젝트에 추가해야 합니다. Maven을 사용하는 경우, pom.xml 파일에 다음 의존성을 추가합니다.

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.11.0</version>
</dependency>

Gradle을 사용하는 경우, build.gradle 파일에 다음과 같이 추가합니다.

implementation group: 'commons-io', name: 'commons-io', version: '2.11.0'

의존성을 추가한 후, 프로젝트를 업데이트하거나 다시 빌드해야 합니다.

2. 압축 파일에서 특정 파일 추출

다음으로, 압축 파일 내의 특정 파일을 추출하는 코드를 작성해야 합니다. 아래는 압축 파일에서 특정 파일을 추출하는 예제 코드입니다.

import org.apache.commons.io.IOUtils;
import org.apache.commons.io.FileUtils;

import java.io.*;
import java.net.URL;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipFileDownloader {

    public static void main(String[] args) throws IOException {
        String zipFileUrl = "https://example.com/archive.zip";
        String targetFileName = "file.txt";

        URL url = new URL(zipFileUrl);
        try (InputStream in = url.openStream();
             ZipInputStream zipIn = new ZipInputStream(in)) {

            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                if (entry.getName().equals(targetFileName)) {
                    File outputFile = new File(targetFileName);
                    try (OutputStream out = new FileOutputStream(outputFile)) {
                        IOUtils.copy(zipIn, out);
                    }
                    break;
                }
            }
        }
    }
}

위 코드는 zipFileUrl에서 지정된 URL에서 압축 파일을 다운로드하고, targetFileName으로 지정된 파일을 추출합니다.

3. 웹에서 파일 다운로드

마지막으로, 위에서 추출한 파일을 웹에서 다운로드할 수 있도록 웹 애플리케이션에 추가합니다. 웹 애플리케이션의 특정 엔드포인트를 만들어 클라이언트가 해당 파일을 다운로드할 수 있도록 합니다.

import org.springframework.util.FileCopyUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FileDownloadController {

    @GetMapping("/downloadFile")
    public ResponseEntity<byte[]> downloadFile() throws IOException {
        Resource resource = new ClassPathResource("file.txt");
        byte[] fileData = FileCopyUtils.copyToByteArray(resource.getFile());

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType("application/octet-stream"));
        headers.setContentDispositionFormData("attachment", "file.txt");
        return new ResponseEntity<>(fileData, headers, HttpStatus.OK);
    }
}

위의 예제는 Spring Framework를 사용하여 웹 애플리케이션을 만듭니다. downloadFile 엔드포인트를 통해 클라이언트가 file.txt 파일을 다운로드할 수 있도록 합니다.

이제 자바를 사용하여 압축 파일 내의 특정 파일을 웹에서 다운로드할 수 있게 되었습니다.

이 글은 Apache Commons IOSpring Framework 공식 문서를 참고하여 작성되었습니다.