JSoup下载文件或图片保存到本地

JSoup下载文件或图片保存到本地

public static void main(String[] args) throws IOException {
        //下载文件的地址
        String fileUrl = "http://image.baidu.com/search/detail?ct=503316480&z=0&ipn=d&word=%E5%9B%BE%E7%89%87&step_word=&hs=0&pn=1&spn=0&di=64680&pi=0&rn=1&tn=baiduimagedetail&is=0%2C0&istype=2&ie=utf-8&oe=utf-8&in=&cl=2&lm=-1&st=-1&cs=2229864841%2C4232235061&os=1657753798%2C2900886188&simid=4281798412%2C697443542&adpicid=0&lpn=0&ln=1707&fr=&fmq=1578399006805_R&fm=&ic=undefined&s=undefined&hd=undefined&latest=undefined&copyright=undefined&se=&sme=&tab=0&width=undefined&height=undefined&face=undefined&ist=&jit=&cg=&bdtype=0&oriquery=&objurl=http%3A%2F%2Ffile02.16sucai.com%2Fd%2Ffile%2F2014%2F0704%2Fe53c868ee9e8e7b28c424b56afe2066d.jpg&fromurl=ippr_z2C%24qAzdH3FAzdH3F8mf7vwt_z%26e3Bv54AzdH3Fda89AzdH3Fa0AzdH3F99ndm_z%26e3Bip4s&gsm=&rpstart=0&rpnum=0&islist=&querylist=&force=undefined";
        Connection connection = Jsoup.connect(fileUrl);
        Connection.Response response = connection.method(Connection.Method.GET).ignoreContentType(true).timeout(3*1000).execute();
        BufferedInputStream bufferedInputStream = response.bodyStream();
        System.out.println(response.contentType());
        saveFile(bufferedInputStream,"C:\\Users\\19167\\Desktop\\1.jpg");//保存文件的地址
    }
/**
     * 保存文件到本地
     * @param bufferedInputStream
     * @param savePath
     */
    public static void saveFile(BufferedInputStream bufferedInputStream,String savePath) throws IOException {
        //一次最多读取1k
        byte[] buffer = new byte[1024];
        //实际读取的长度
        int readLenghth;
        //根据文件保存地址,创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
        //创建的一个写出的缓冲流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        //文件逐步写入本地
        while ((readLenghth = bufferedInputStream.read(buffer,0,1024)) != -1){//先读出来,保存在buffer数组中
            System.out.println(readLenghth);
            bufferedOutputStream.write(buffer,0,readLenghth);//再从buffer中取出来保存到本地
        }
        //关闭缓冲流
        bufferedOutputStream.close();
        fileOutputStream.close();
        bufferedInputStream.close();
    }

在下编程小白,如果有什么错误希望大家批评指正!
邮箱:1916728303@qq.com
更多网络爬虫知识可以参考:
网络爬虫

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值