java 实现爬虫的方法

java 实现爬虫的方法

一、意义

通过实现爬虫的方法,实现对IO类的学习。

二、方法

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Url {
    //爬虫下载
    public static void down(String s,String res) {
        HttpURLConnection con =null;
        InputStream is =null;
        FileOutputStream fos =null;
        try {
        URL url = new URL(s);
        con = (HttpURLConnection) url.openConnection();
        is = con.getInputStream();
        fos = new FileOutputStream(res);
        byte[] buffer = new byte[1024];
        int len;
        while((len=is.read(buffer))!=-1){
            fos.write(buffer,0,len);
        }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            con.disconnect();
        }
    }
}

三、使用例子

    public static void main(String[] args){
        String s= "https://dl.stream.qqmusic.qq.com/RS02061fi2i40D17Ru.mp3?guid=6592987690&vkey=A4EC1E54E7CD264F9BE9E94C11FE94455D18F7F1EF9E16762D9D503872735501573A5D2B9B1D7F27B2913376625892926517A3D1650B3A8A&uin=&fromtag=120052";
        String res="f.mp3";
        down(s,res);
    }

输出:一首超级好听的歌曲

f.mp3

四、结尾

本方法经过本人多次分析与测试,如有更好的方法或者发现错误的地方欢迎大家评论与指正!

  • 7
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值