从链接中下载文件

本文采用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();
		}
	}

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值