內容
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(); } }