아빠는 개발자

[java] URL 호출해서 파일 다운로드 (InputStream) 본문

Java

[java] URL 호출해서 파일 다운로드 (InputStream)

father6019 2024. 6. 1. 22:53
728x90
반응형

URL 을 호출해서 파일 다운로드를 해보잣

간단하게는 아래와 같이InputStream을 사용하여 URL에서 데이터를 읽고, Files.copy 메서드를 사용하여 파일로 저장하는 방법으로 만들 수도 있으나..

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileDownload {
    public static void main(String[] args) {
        String fileURL = "https://example.com/path/to/file.txt"; // 다운로드할 파일의 URL
        String saveDir = "/path/to/save/directory"; // 파일을 저장할 디렉토리

        try {
            downloadFile(fileURL, saveDir);
            System.out.println("파일 다운로드 완료.");
        } catch (IOException e) {
            System.out.println("파일 다운로드 중 오류 발생: " + e.getMessage());
        }
    }

    public static void downloadFile(String fileURL, String saveDir) throws IOException {
        // URL 객체 생성
        URL url = new URL(fileURL);
        // URL로부터 InputStream 열기
        try (InputStream inputStream = url.openStream()) {
            // 저장할 파일 경로 생성
            Path savePath = Paths.get(saveDir, Paths.get(url.getPath()).getFileName().toString());
            // InputStream을 파일로 복사
            Files.copy(inputStream, savePath);
        }
    }
}

 

 

 Java NIO (New I/O) 라이브러리를 사용하여 더 나은 성능으로 만들어보자 . 또한, Files.copy 메서드에 StandardCopyOption.REPLACE_EXISTING 옵션을 추가하여 동일한 파일이 있을 경우 덮어쓰도록 구성

왜냐면 어차피 날짜별로 가져올꺼라.. 여러 파일이 있어봤자.. 중복이 대부분일터..

 

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class FileDownload {
    public static void main(String[] args) {
        String fileURL = "https://example.com/path/to/file.txt"; // 다운로드할 파일의 URL
        String saveDir = "/path/to/save/directory"; // 파일을 저장할 디렉토리

        try {
            downloadFile(fileURL, saveDir);
            System.out.println("파일 다운로드 완료.");
        } catch (IOException e) {
            System.out.println("파일 다운로드 중 오류 발생: " + e.getMessage());
        }
    }

    public static void downloadFile(String fileURL, String saveDir) throws IOException {
        URL url = new URL(fileURL);
        HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
        int responseCode = httpConn.getResponseCode();

        // HTTP 응답 코드 확인
        if (responseCode == HttpURLConnection.HTTP_OK) {
            String fileName = "";
            String disposition = httpConn.getHeaderField("Content-Disposition");

            // 파일 이름 추출
            if (disposition != null && disposition.contains("filename=")) {
                int index = disposition.indexOf("filename=");
                if (index > 0) {
                    fileName = disposition.substring(index + 10, disposition.length() - 1);
                }
            } else {
                // URL에서 파일 이름 추출
                fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1);
            }

            // 파일 저장 경로 생성
            Path savePath = Paths.get(saveDir, fileName);

            // InputStream 열기
            try (InputStream inputStream = httpConn.getInputStream()) {
                // 파일 저장
                Files.copy(inputStream, savePath, StandardCopyOption.REPLACE_EXISTING);
            }

            System.out.println("File downloaded to " + savePath.toString());
        } else {
            System.out.println("No file to download. Server replied HTTP code: " + responseCode);
        }
        httpConn.disconnect();
    }
}
728x90
반응형

'Java' 카테고리의 다른 글

[java] Vavr 란?  (0) 2024.09.02
[java] package 에서 common 과 base 의 의미  (0) 2024.06.11
[java] Unix 타임스탬프  (0) 2024.06.01
[JPA] CRUD 구현하기  (0) 2024.04.10
[java] 이벤트 리스너 @EventListener  (0) 2024.03.31