通过Url下载网络资源
程序员文章站
2022-05-05 20:42:47
...
步骤
- 通过下载地址创建url对象
- 连接到这个资源的http
- 从获取输入流
- 读取并写入
- 关闭连接
具体代码
package Url;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class UrlDown {
public static void main(String[] args) throws Exception {
//1.通过下载地址创建url对象
URL url = new URL("https://i1.hdslb.com/bfs/face/[email protected]_140h_1c.webp");
//2.连接到这个资源的http
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//3.从获取输入流
InputStream inputStream = urlConnection.getInputStream();
//4.读取并写入
byte[] buffer = new byte[1024];
int len;
FileOutputStream fileOutputStream = new FileOutputStream(new File("3.jpg"));
while((len=inputStream.read(buffer)) != -1){
fileOutputStream.write(buffer,0,len);
}
//5.关闭连接
fileOutputStream.close();
inputStream.close();
urlConnection.connect();
}
}
上一篇: 3.URL下载网络资源
下一篇: 通过URL下载网络资源