本文采用Java中的URL技术从指定链接中下载资源。
package cn.nwsuaf.url;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
/**
* 从链接中下载文件
*
* @author 刘永浪
*
*/
public class URLDemo {
public static void main(String[] args) {
try {
// 定义URL对象并传入链接参数
URL url = new URL(
"http://g.hiphotos.baidu.com/image/pic/item/a8ec8a13632762d00905bd2da2ec08fa513dc66d.jpg");
// 输出本地主机名
System.out.println("主机名:" + url.getHost());
// 输出资源路径
System.out.println("资源路径:" + url.getPath());
// 输出端口号
System.out.println("端口号:" + url.getPort());
// 输出协议(http、ftp、file协议)
System.out.println("协议:" + url.getProtocol());
// 通过URL打开连接
URLConnection conn = url.openConnection();
// 设置文件存储路径
String path = url.getPath().substring(
url.getPath().lastIndexOf("/"));
System.out.println(path);
// 保存下载文件到本地资源
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
BufferedOutputStream fos = new BufferedOutputStream(
new FileOutputStream("d:" + path));
byte[] bytes = new byte[1024 * 10];
int len = -1;
while ((len = bis.read(bytes)) != -1) {
fos.write(bytes, 0, len);
fos.flush();
}
fos.close();
bis.close();
System.out.println("下载成功!");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}