使用 jsoup 下载图片

来源:互联网 发布:网络延迟不稳定 编辑:程序博客网 时间:2024/05/22 10:50

问题描述:
某次任务需要使用大量Logo以及背景图, 但是这些图片在某服务器上, 而且打开网址后显示的图片是以链接的形式存在, 如: logo1.jpg, 必须点开一张张下载,所以产生了下面的代码:

import java.io.File;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.regex.Pattern;import org.jsoup.Jsoup;import org.jsoup.nodes.Document;import org.jsoup.nodes.Element;import org.jsoup.select.Elements;public class ImgDownloader{    public void getDoc() throws IOException {        File f = new File("E:\\imgs");        if (!f.exists()) {            f.mkdirs();        }        String picUrl = "http://xxx.com/images/";        Document doc = Jsoup.connect(picUrl).get();        Elements links = doc.select("a[href]");        for (Element e : links) {            if (Pattern.matches(".*?jpe?g|png|git$", e.attr("href"))) {                String src = e.absUrl("href");                String imageName = src.substring(src.lastIndexOf("/") + 1, src.length());                URL url = new URL(src);                URLConnection uri = url.openConnection();                InputStream is = uri.getInputStream();                OutputStream os = new FileOutputStream(new File("E:/imgs/homed", imageName));                byte[] buf = new byte[1024];                int len = -1;                while ((len = is.read(buf)) != -1) {                    os.write(buf, 0, len);                }            }        }    }    public static void main(String[] args) throws IOException {        new ImgDownloader().getDoc();    }}
0 0
原创粉丝点击