存储在网络上的图片
package test22;
import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
/**
* Created By Intellij IDEA
*
* @author Xinrui Yu
* @date 2021/12/6 15:05 星期一
*/
public class UrlTest {
public static void main(String[] args) {
FileOutputStream fileOutputStream = null;
BufferedOutputStream bufferedOutputStream = null;
try {
fileOutputStream = new FileOutputStream("URLIMG.png");
bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
// 通过 URL 来请求存储在网络上的资源文件
URL url = new URL("https://cdn.jsdelivr.net/gh/yxr2333/imgContainer/20211129151123.png");
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.connect();
// 获得文件的输入流
InputStream inputStream = urlConnection.getInputStream();
int len;
byte[] buffer = new byte[1024];
// 通过文件的输入流,将文件下载到本地
while((len = inputStream.read(buffer)) != -1){
bufferedOutputStream.write(buffer,0,len);
}
System.out.println("图片资源下载完毕!");
// 关闭必要的资源连接
inputStream.close();
urlConnection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}finally {
if(bufferedOutputStream != null){
try {
bufferedOutputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
运行程序,图片可以成功的从网络上下载下来。