java url抓取文件到本地

2019-05-09 11:43:30 浏览数 (1)

代码语言:javascript复制
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");
}

0 人点赞