java下載網絡數據

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);
    }
}

發佈了33 篇原創文章 · 獲贊 4 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章