Java 使用java的URL类通过url下载网络资源

ゞ 浴缸里的玫瑰 2021-09-21 13:32 432阅读 0赞

主要用到的类

  • 地址类: URL
  • http类: HttpURLConnection
  • 输入流: InputStream
  • 输出流: FileOutputStream

上代码

  1. package com.demo01;
  2. import java.io.FileOutputStream;
  3. import java.io.InputStream;
  4. import java.net.HttpURLConnection;
  5. import java.net.URL;
  6. import java.util.Random;
  7. public class TestURL {
  8. public static void main(String[] args) throws Exception {
  9. // 下载地址
  10. String downURL = "https://dss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=2771978851,2906984932&fm=26&gp=0.jpg";
  11. // 地址
  12. URL url = new URL(downURL);
  13. // 获取文件后缀名
  14. String fileName = "";
  15. int index = url.getFile().lastIndexOf(".");
  16. if (index != -1) {
  17. fileName = url.getFile().substring(index);
  18. }
  19. // 打开地址
  20. HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
  21. // 获取流
  22. InputStream is = urlConnection.getInputStream();
  23. // 写入流
  24. Random random = new Random();
  25. FileOutputStream fos = new FileOutputStream("UrlDown" + random.nextInt(1000) + fileName);
  26. // 写入文件
  27. byte[] buffer = new byte[1024];
  28. int len;
  29. while ((len = is.read(buffer)) != -1) {
  30. fos.write(buffer,0,len);
  31. }
  32. // 关闭流
  33. fos.close();
  34. is.close();
  35. urlConnection.disconnect(); // 断开连接
  36. }
  37. }

发表评论

表情:
评论列表 (有 0 条评论,432人围观)

还没有评论,来说两句吧...

相关阅读