通过URL地址下载服务器上的文件
/**
* URL编程测试
* 通过URL地址下载服务器上的文件
*/
public class URLTest {
public static void main(String[] args) {
//服务器图片地址
String imageUrl = "http://img33.igusoft.com/upl2oads/2021/fw253zpi41m.jpg";
//获取URL对象
URL url = null;
HttpURLConnection connection = null;
InputStream is = null;
FileOutputStream fos = null;
try {
url = new URL(imageUrl);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
is = connection.getInputStream();
fos = new FileOutputStream("美女图片.jpg");
byte[] buffer = new byte[1024];
int len = 0;
while ((len = is.read(buffer)) != -1) {
fos.write(buffer, 0, len);
}
System.out.println("图片下载成功");
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭流
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (is != null) {
try {
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
if (connection != null) {
connection.disconnect();
}
}
}
}