java爬虫技术学习-jsoup框架的练习题目之一

java爬虫技术学习-jsoup框架的练习题目之一!

{

* jsoup实现缓冲数据流,下载网络资源到本地硬盘

}

下面给大家帖上原始的代码,亲测有效。

可以下载图片,文件,文档,视频,音乐等内容。

package inputstream;

import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.*;

/**
 * jsoup实现缓冲数据流,下载网络资源到本地硬盘
 */
public class JsoupInputStream {
    static void saveImg(BufferedInputStream in,String savePath) throws IOException {
        byte[] buffer = new byte[1024];
        int len = 0;
        //创建缓冲流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
       BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
       //图片写入
        while((len = in.read(buffer,0,1024))!= -1){
            bufferedOutputStream.write(buffer,0,len);
        }
        //缓冲流释放与关闭
        bufferedOutputStream.flush();
        bufferedOutputStream.close();

    }
    public static void main(String[] args) throws IOException {
        String imgUrl = "https://mmbiz.qpic.cn/sz_mmbiz_jpg/ssDMeQm2ZOTDJEY62uvaPMbdCZ8QI56c2zvtgg3YL1rerVFwsBFxqTOcfIibic73pHGSV0KJGicJeliaqwQIz8TBQQ/640?wx_fmt=jpeg";
        Connection connection = Jsoup.connect(imgUrl);
        Connection.Response response = connection.method(Connection.Method.GET).ignoreContentType(true).execute();
        System.out.println("文件类型为:"+ response.contentType());
        //响应转化为输出流
        BufferedInputStream bufferedInputStream = response.bodyStream();
        //保存图片
        saveImg(bufferedInputStream,"E://image//12.jpg");
        System.out.println("下载完毕");

    }
}

欢迎大家交流互动,讨论,jsoup爬虫技术。本人在自学java爬虫的内容。

你可能感兴趣的:(jsoup,java,爬虫,学习)