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
四、结尾
本方法经过本人多次分析与测试,如有更好的方法或者发现错误的地方欢迎大家评论与指正!