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 }
时间: 2024-10-21 00:14:31