您的位置:首页 > 其它

URL,下载网页图片。

2016-03-05 22:56 246 查看
import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.net.URL;

import java.net.URLConnection;

import java.util.UUID;

//下载网站图片并保存在D盘

public class TestURL {

 public static void main(String[] args) throws IOException {

  URL url = new URL("http://b.zol-img.com.cn/desk/bizhi/image/3/1680x1050/1376276329221.jpg");  //下载图片的网页地址

  URLConnection conn = url.openConnection();

  InputStream in = conn.getInputStream();

  String contentType = conn.getContentType();//image/jpeg

  String ext = "";

  if("image/jpeg".equals(contentType)){

   ext = ".jpg";

  }else if("image/png".equals(contentType)){

   ext = ".png";

  }else if("image/bmp".equals(contentType)){

   ext = ".bmp";

  }else if("image/gif".equals(contentType)){

   ext = ".gif";

  }

  

  //输入流

  OutputStream out = new FileOutputStream("D:\\"+UUID.randomUUID()+ext);//UUID是唯一的标识字符串名

  

  byte[] buf = new byte[1024*4];

  int len = -1;

  while((len=in.read(buf))!=-1){

   out.write(buf,0,len);

  }

  out.flush();

  System.out.println("下载完成");

 }

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: