首页 > 编程语言 > 详细

java 下载网上图片

时间:2020-06-03 16:53:39      阅读:47      评论:0      收藏:0      [点我收藏+]

webmagic抓取某网站的图片,需要保存图片。

 

import java.io.*;
import java.net.URL;
import java.net.URLConnection;

public class FileDownloader {

    public static void download(String urlStr, String destDir, String... newFileName) throws IOException {

        if (null == urlStr || "".equalsIgnoreCase(urlStr)) {
            return;
        }

        URL url = new URL(urlStr);
        URLConnection connection = url.openConnection();
        connection.setConnectTimeout(5000);
        InputStream in = connection.getInputStream();
        byte[] bytes = new byte[1024];
        int len;
        File file = new File(destDir);
        if (!file.exists()) {
            file.mkdirs();
        }

        String[] split = urlStr.split("/");
        String fileName = split[split.length - 1];

        if (newFileName != null && newFileName.length > 0) {
            fileName = newFileName[0] + "." + fileName.split("\\.")[1];
        }

        OutputStream out = new FileOutputStream(file.getPath() + "/" + fileName);
        while ((len = in.read(bytes)) != -1) {
            out.write(bytes, 0, len);
        }
        out.close();
        in.close();
    }

 

java 下载网上图片

原文:https://www.cnblogs.com/luohaonan/p/13038091.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!