Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.File;
- import java.io.IOException;
- import java.io.InputStream;
- import java.net.URI;
- import java.net.URISyntaxException;
- import java.net.http.HttpClient;
- import java.net.http.HttpRequest;
- import java.net.http.HttpResponse;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.util.Collection;
- public class DownloadService {
- HttpClient client = HttpClient.newBuilder().build();
- public Path downloadFile(String sourceUrl) throws URISyntaxException, IOException, InterruptedException {
- HttpRequest httpRequest = HttpRequest
- .newBuilder()
- .uri(new URI(sourceUrl))
- .GET()
- .build();
- String fileName = sourceUrl.substring(sourceUrl.lastIndexOf('/') + 1);
- HttpResponse<InputStream> response = client
- .send(httpRequest, responseInfo ->
- HttpResponse.BodySubscribers.ofInputStream());
- if (response.statusCode() != 200) {
- throw new RuntimeException("Ошибка при скачивании");
- }
- Path targetPath = new File("src/main/resources/" + File.separator + fileName).toPath();
- Files.copy(response.body(), targetPath);
- return targetPath;
- }
- }
- import java.io.File;
- import java.net.MalformedURLException;
- import java.net.URL;
- import java.nio.file.Path;
- import java.util.Locale;
- public class Main {
- public static void main(String[] args) throws MalformedURLException {
- if (args.length != 1) {
- throw new RuntimeException("Не указан путь до файла");
- }
- DownloadService service = new DownloadService();
- String url = args[0];
- Path downloadedFile;
- try {
- downloadedFile = service.downloadFile(url);
- } catch (Exception e) {
- throw new RuntimeException("Ошибка при скачивании файла", e);
- }
- System.out.println(downloadedFile);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement