从链接中下载文件

来源:互联网 发布:飞鹰网络电视安卓版 编辑:程序博客网 时间:2024/05/22 10:57

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


 

1 0
原创粉丝点击