URL统一资源定位符
协议://ip地址:端口/项目名/资源
下载网络资源到本地
package com.li.changGe.urlDownload;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
public class URLFileDownload {
public static void main(String[] args) {
new URLFileDownload().download();
}
public void download(){
InputStream inputStream = null;
FileOutputStream fileOutputStream = null;
try {
URL url = new URL("https://tse2-mm.cn.bing.net/th/id/OIP-C.DXKj0u8XttHNJorm0vUooAHaEK?pid=ImgDet&rs=1");
URLConnection urlConnection = url.openConnection();
inputStream = urlConnection.getInputStream();
fileOutputStream = new FileOutputStream("迎风飘扬的旗.jpeg");
byte[] bytes = new byte[1024];
int length;
while ((length = inputStream.read(bytes)) != -1){
fileOutputStream.write(bytes,0,length);
}
System.out.println("文件输出完毕");
}catch (Exception e){
System.out.println("文件找不到");
e.printStackTrace();
}finally {
if(fileOutputStream != null){
try {
fileOutputStream.close();
}catch (Exception e){
e.printStackTrace();
System.out.println("文件输出流关闭错误");
}
}
if(inputStream != null){
try {
inputStream.close();
}catch (Exception e){
e.printStackTrace();
System.out.println("文件输入流关闭错误");
}
}
}
}
}