使用java語言爬取網絡圖片並下載到本地

我們經常會在網絡上瀏覽到很多圖片,有時候會想要下載下來。這次就嘗試着用java代碼把圖片給下載到電腦上。

先下載一張圖片試試。

圖片的鏈接是:http://img03.sogoucdn.com/app/a/100520093/3c28af542f2d49f7-8331c86ff317d9f5-8ee52078d03feac9b8502dad26f33c31.jpg

要下載的圖片爲:


以下代碼爲下載此圖片的代碼(完整代碼,經測試):

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

public class Test {
	public static InputStream inStream = null;
	public static void main(String[] args){
		try {
			//要訪問的圖片鏈接
			URL url = new URL("http://img03.sogoucdn.com/app/a/100520093/3c28af542f2d49f7-8331c86ff317d9f5-8ee52078d03feac9b8502dad26f33c31.jpg");
			//建立網絡連接
			URLConnection con = url.openConnection();
			inStream = con.getInputStream();
			//中轉站,現將圖片數據放到outStream中
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = inStream.read(buf)) != -1){
				outStream.write(buf,0,len);
			}
			inStream.close();
			outStream.close();
			File file = new File("f://a.jpg"); //圖片下載的位置
			FileOutputStream op = new FileOutputStream(file);
			op.write(outStream.toByteArray());
			op.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
然後看下F盤下的內容:

這樣表示下載完成了。

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