存储在网络上的图片
    image.png

    1. package test22;
    2. import javax.net.ssl.HttpsURLConnection;
    3. import java.io.BufferedOutputStream;
    4. import java.io.FileOutputStream;
    5. import java.io.IOException;
    6. import java.io.InputStream;
    7. import java.net.URL;
    8. /**
    9. * Created By Intellij IDEA
    10. *
    11. * @author Xinrui Yu
    12. * @date 2021/12/6 15:05 星期一
    13. */
    14. public class UrlTest {
    15. public static void main(String[] args) {
    16. FileOutputStream fileOutputStream = null;
    17. BufferedOutputStream bufferedOutputStream = null;
    18. try {
    19. fileOutputStream = new FileOutputStream("URLIMG.png");
    20. bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
    21. // 通过 URL 来请求存储在网络上的资源文件
    22. URL url = new URL("https://cdn.jsdelivr.net/gh/yxr2333/imgContainer/20211129151123.png");
    23. HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
    24. urlConnection.connect();
    25. // 获得文件的输入流
    26. InputStream inputStream = urlConnection.getInputStream();
    27. int len;
    28. byte[] buffer = new byte[1024];
    29. // 通过文件的输入流,将文件下载到本地
    30. while((len = inputStream.read(buffer)) != -1){
    31. bufferedOutputStream.write(buffer,0,len);
    32. }
    33. System.out.println("图片资源下载完毕!");
    34. // 关闭必要的资源连接
    35. inputStream.close();
    36. urlConnection.disconnect();
    37. } catch (IOException e) {
    38. e.printStackTrace();
    39. }finally {
    40. if(bufferedOutputStream != null){
    41. try {
    42. bufferedOutputStream.close();
    43. } catch (IOException e) {
    44. e.printStackTrace();
    45. }
    46. }
    47. }
    48. }
    49. }

    运行程序,图片可以成功的从网络上下载下来。
    image.png