使用URLConnection下载文件或图片并保存到本地

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

/**
* 使用URLConnection下载文件或图片并保存到本地。
*/
public class URLConnectionDownloader {
public static void main(String[] args) throws Exception {
String url = "http://mt1.google.cn/vt/v=w2.114&hl=zh-CN&gl=cn&x=1&y=1&z=1";
// String url = "http://www.google.cn/intl/zh-CN/images/logo_cn.gif";
String fileDir = "d:\\a\\";
String fileName = "abc.jpg";

makeDir(fileDir);
download(url, fileDir+fileName);

System.out.println("下载图片完毕!");
}

/**
* 下载文件到本地
*
* @param urlString
*            被下载的文件地址
* @param filename
*            本地文件名
* @throws Exception
*             各种异常
*/
public static void download(String urlString, String filename)
throws Exception {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();

// 设置Java服务器代理连接,要不然报错403
// 浏览器可以访问此url图片并显示,但用Java程序就不行报错Server returned HTTP response code:403 for URL
// 具体原因:服务器的安全设置不接受Java程序作为客户端访问(被屏蔽),解决办法是设置客户端的User Agent
con.setRequestProperty("User-Agent", "Mozilla/4.0(compatible;MSIE 5.0;Windows NT;DigExt)");

// 输入流
InputStream is = con.getInputStream();

// 1K的数据缓冲
byte[] bs = new byte[1024];
// 读取到的数据长度
int len;
// 输出的文件流
OutputStream os = new FileOutputStream(filename);
// 开始读取
while ((len = is.read(bs)) != -1) {
os.write(bs, 0, len);
}
// 完毕,关闭所有链接
os.close();
is.close();
}

private static void makeDir(String fileFolder) {
File file = new File(fileFolder);
if (!file.exists() && !file.isDirectory())
file.mkdir();
}
}

猜你喜欢

转载自jie66989.iteye.com/blog/1691681