比如因特网上有一图片资源http://img.7799520.com/00356c0e-1725-4dc2-b091-5db958b6c637,现在要把该资源下载到本地,下面介绍如下两种方式。
方式一:
/*first advice*/
/*
* urlHttp = "http://img.7799520.com/00356c0e-1725-4dc2-b091-5db958b6c637"
* path = "e:/picture"
* */
public static void getPicture(String urlHttp, String path){
String file = path + "/" + new Date().getTime() + ".jpg";
try {
URL url = new URL(urlHttp);
BufferedImage img = ImageIO.read(url);
ImageIO.write(img, "jpg", new File(file));
} catch (Exception e) {
e.printStackTrace();
}
}
运行程序,会在e:/picture下创建一个以当前时间戳命名的jpg格式的照片。
方式二:
/*second advice*/
/*
* urlHttp = "http://img.7799520.com/00356c0e-1725-4dc2-b091-5db958b6c637"
* path = "e:/picture"
* */
public static void getPicture2(String urlHttp, String path){
FileOutputStream out = null;
BufferedInputStream in = null;
HttpURLConnection connection = null;
byte[] buf = new byte[1024];
int len = 0;
try {
URL url = new URL(urlHttp);
connection = (HttpURLConnection)url.openConnection();
connection.connect();
in = new BufferedInputStream(connection.getInputStream());
out = new FileOutputStream(path + "/" + new Date().getTime() + ".jpg");
while ((len = in.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
connection.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
}
运行程序,生成结果同方式一