码迷,mamicode.com
首页 > 编程语言 > 详细

java学习之url

时间:2016-01-24 00:24:00      阅读:190      评论:0      收藏:0      [点我收藏+]

标签:

 1 package com.gh.URL;
 2 import java.io.BufferedInputStream;
 3 import java.io.BufferedOutputStream;
 4 import java.io.FileOutputStream;
 5 import java.io.IOException;
 6 import java.net.URL;
 7 import java.net.URLConnection;
 8 /**
 9  * 利用url下载文件
10  * 
11  * @author ganhang
12  *
13  */
14 public class URLDemo {
15     public static void main(String[] args) {
16         try {
17             URL url=new URL("http://localhost:8080/hehe/1.jpg");//tomcat启动一个服务器
18             //System.out.println("内容:"+url.getContent());//获得内容
19             System.out.println("主机名:"+url.getHost());//获得主机名
20             System.out.println("路径:"+url.getPath());//获得路径
21             System.out.println("端口号:"+url.getPort());//获得端口号
22             System.out.println("协议:"+url.getProtocol());
23             URLConnection conn= url.openConnection();//获得连接对象
24             //获得连接对象的字节缓存输入流
25             //上传用getOutputStream()
26             BufferedInputStream bis= new BufferedInputStream(conn.getInputStream());
27             //下载到当前目录的缓存输出流
28             BufferedOutputStream bos =new BufferedOutputStream(new FileOutputStream("1.jpg"));
29             int len =-1;
30             byte[] b =new byte[1024];
31             while((len=bis.read(b))!=-1){
32                 bos.write(b,0,len);
33                 bos.flush();
34             }
35             bis.close();
36             bos.close();
37             System.out.println("下载成功");
38         } catch (IOException e) {
39             e.printStackTrace();
40         }
41     }
42 }

 

java学习之url

标签:

原文地址:http://www.cnblogs.com/ganhang-acm/p/5154375.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!