URL,下載網頁圖片。

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("下載完成");
 }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章