java下载网络数据

来源:互联网 发布:新卷皮 淘宝客 源码 编辑:程序博客网 时间:2024/04/26 06:22
package com.network;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/*
 *  下载网络上的数据(图片,文件,视频)
 */
public class DownloadFile
{
    public static  void download(String urlpath,String filename,String savepath)
    {
        try {
            URL  url = new URL(urlpath);
            URLConnection conn= url.openConnection();
            conn.setConnectTimeout(5000);
            InputStream  in  = conn.getInputStream();
            File path = new File(savepath);
            if(!path.exists())
            {
                path.mkdirs();
            }
            OutputStream out = new  FileOutputStream(path.getPath()+"\\"+filename);
            int len =0;
            byte[] b = new byte[2048];
            while((len=in.read(b))!=-1)
            {
                out.write(b, 0, len);
            }
        
          }
        catch (MalformedURLException e)
        {    
            e.printStackTrace();
        } catch (IOException e)
        {
            
            e.printStackTrace();
        }    
    }
    public static   void  main(String[] args)
    {
        String path ="http://www.verydemo.com/demo_c98_i4648.html";
        String filename="myfile.html";
        String savepath = "d:/image";
        download(path,filename,savepath);
    }
}