Advertisement
LeatherDeer

Untitled

Nov 14th, 2022
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.03 KB | None | 0 0
  1. import java.io.File;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.net.URI;
  5. import java.net.URISyntaxException;
  6. import java.net.http.HttpClient;
  7. import java.net.http.HttpRequest;
  8. import java.net.http.HttpResponse;
  9. import java.nio.file.Files;
  10. import java.nio.file.Path;
  11. import java.util.Collection;
  12.  
  13. public class DownloadService {
  14. HttpClient client = HttpClient.newBuilder().build();
  15.  
  16.  
  17. public Path downloadFile(String sourceUrl) throws URISyntaxException, IOException, InterruptedException {
  18. HttpRequest httpRequest = HttpRequest
  19. .newBuilder()
  20. .uri(new URI(sourceUrl))
  21. .GET()
  22. .build();
  23. String fileName = sourceUrl.substring(sourceUrl.lastIndexOf('/') + 1);
  24.  
  25. HttpResponse<InputStream> response = client
  26. .send(httpRequest, responseInfo ->
  27. HttpResponse.BodySubscribers.ofInputStream());
  28.  
  29. if (response.statusCode() != 200) {
  30. throw new RuntimeException("Ошибка при скачивании");
  31. }
  32.  
  33. Path targetPath = new File("src/main/resources/" + File.separator + fileName).toPath();
  34. Files.copy(response.body(), targetPath);
  35.  
  36. return targetPath;
  37. }
  38. }
  39.  
  40.  
  41.  
  42.  
  43. import java.io.File;
  44. import java.net.MalformedURLException;
  45. import java.net.URL;
  46. import java.nio.file.Path;
  47. import java.util.Locale;
  48.  
  49. public class Main {
  50.  
  51.  
  52. public static void main(String[] args) throws MalformedURLException {
  53. if (args.length != 1) {
  54. throw new RuntimeException("Не указан путь до файла");
  55. }
  56. DownloadService service = new DownloadService();
  57. String url = args[0];
  58.  
  59. Path downloadedFile;
  60.  
  61. try {
  62. downloadedFile = service.downloadFile(url);
  63. } catch (Exception e) {
  64. throw new RuntimeException("Ошибка при скачивании файла", e);
  65. }
  66.  
  67. System.out.println(downloadedFile);
  68. }
  69. }
  70.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement