Java

url抓取文件到本地

2014/03/02 18:06 6266 次阅读王梓
★ 打赏
✸ ✸ ✸

 

package socket;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Date;

public class Url {

public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
URL url=new URL("http://www.liezi.net/wp-content/uploads/2014/02/bailai1.mp3");
System.out.println(url.getHost());
System.out.println(url.getPath());
System.out.println(url.getPort());
System.out.println(url.getProtocol());
Date date=new Date();
System.out.println(date);

String filename=url.getPath().substring(url.getPath().lastIndexOf("/"));
URLConnection conn=url.openConnection();
BufferedInputStream bis=new BufferedInputStream(conn.getInputStream());
BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream("c:\\test"+filename));
byte[] bytes=new byte[1024*100];
int len=-1;
int i=1;
while((len=bis.read(bytes))!=-1){
bos.write(bytes,0,len);
bos.flush();

i++;
System.out.println(i);
}
bos.close();
bis.close();
System.out.println("downloaded");
}
 

 

✸ ✸ ✸

📜 版权声明

本文作者:王梓 | 原文链接:https://www.bthlt.com/note/10414773-Javaurl抓取文件到本地

出处:葫芦的运维日志 | 转载请注明出处并保留原文链接

📜 留言板

留言提交后需管理员审核通过才会显示