java根據圖片路徑下載圖片並保存到本地目錄


內容

import java.io.File;  
import java.io.FileOutputStream;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.net.URL;  
import java.net.URLConnection;  
  
  
public class DownloadImage {  
  
    /** 
     * @param args 
     * @throws Exception  
     */  
    public static void main(String[] args) throws Exception {  
        // TODO Auto-generated method stub  
         download("http://avatar.csdn.net/1/3/B/1_li1325169021.jpg", "1_li1325169021.jpg","d:\\image\\");  
    }  
      
    public static void download(String urlString, String filename,String savePath) throws Exception {  
        // 構造URL  
        URL url = new URL(urlString);  
        // 打開連接  
        URLConnection con = url.openConnection();  
        //設置請求超時為5s  
        con.setConnectTimeout(5*1000);  
        // 輸入流  
        InputStream is = con.getInputStream();  
      
        // 1K的數據緩沖  
        byte[] bs = new byte[1024];  
        // 讀取到的數據長度  
        int len;  
        // 輸出的文件流  
       File sf=new File(savePath);  
       if(!sf.exists()){  
           sf.mkdirs();  
       }  
      // 獲取圖片的擴展名
       String extensionName = filename.substring(filename.lastIndexOf(".") +     1);
       // 新的圖片文件名 = 編號 +"."圖片擴展名
       String newFileName = goods.getProductId()+ "." + extensionName;
       OutputStream os = new FileOutputStream(sf.getPath()+"\\"+filename);  
        // 開始讀取  
        while ((len = is.read(bs)) != -1) {  
          os.write(bs, 0, len);  
        }  
        // 完畢,關閉所有鏈接  
        os.close();  
        is.close();  
    }   
  
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM