jsoup下载图片

package test;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class download {
	public static int num = 0;

	public static void main(String[] args) throws IOException {
		Document doc = Jsoup.connect("http://guju.com.cn/photos/new").get();
		Elements elements = doc.select("img[src]");
		for (Element element : elements) {
			String imgUrl = element.attr("src");
			System.out.println(imgUrl);
			if (!imgUrl.startsWith("http://")) {
				imgUrl = "http:" + imgUrl;
			}
			new Thread(new download().new DownLoadThread(imgUrl)).start();
		}
	}

	public class DownLoadThread implements Runnable {
		private String imgUrl;

		public DownLoadThread(String url) {
			this.imgUrl = url;
		}

		@Override
		public void run() {
			FileOutputStream out = null;
			HttpURLConnection conn = null;
			try {
				URL url = new URL(imgUrl);
				conn = (HttpURLConnection) url.openConnection();
				conn.setRequestMethod("GET");
				conn.setReadTimeout(5 * 1000);
				InputStream inputStream = conn.getInputStream();
				// imgUrl.replaceAll("\\", "_").replaceAll("http:", "");
				String fileName = "e:\\photo\\"+num++ + ".jpg";
				out = new FileOutputStream(new File(fileName));
				byte[] arr = new byte[1024];
				int len = 0;
				while ((len = inputStream.read(arr)) != -1) {
					out.write(arr, 0, len);
				}
				System.out.println("=====处理完成====");
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (out != null) {
					try {
						out.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (conn != null) {
					conn.disconnect();
				}

			}
		}

	}
}

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。