java下载工具类

在实际的java开发中,我们或多或少会涉及到文件的下载,那么只需要你引入以下工具类,即可完成对文件的下载,这个可以运用到java爬虫批量下载图片中.不废话,直接上代码.

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

/**
 * 下载工具类
 *
 * @author: agu
 */
public class DownloadUtil {
    /**
     * usrStr : 图片路径
     * filename: 图片名称
     * savePath: 要保存的路径
     */
    public static void download(String urlStr, String filename, String
            savePath) throws IOException {
        URL url = new URL(urlStr);
        //打开url连接
        URLConnection connection = url.openConnection();
        //请求超时时间
        connection.setConnectTimeout(5000);
        //输入流
        InputStream in = connection.getInputStream();
        //缓冲数据
        byte[] bytes = new byte[1024];
        //数据长度
        int len;
        //文件
        File file = new File(savePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        OutputStream out = new
                FileOutputStream(file.getPath() + "\\" + filename);
        //先读到bytes中
        while ((len = in.read(bytes)) != -1) {
            //再从bytes中写入文件
            out.write(bytes, 0, len);
        }
        //关闭IO
        out.close();
        in.close();
    }

    public static void main(String[] args) throws IOException {

        download("https://avatar.csdnimg.cn/4/4/8/1_weixin_45058795_1581123333.jpg", "博主头像.jpg", "e:/userImage");
    }
}

版权声明:本文为weixin_45058795原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。