1. 程式人生 > >Java下載檔案

Java下載檔案

1.main函式中

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
/**
* @Description:    下載檔案至本地
* @Author:          wangyk
* @CreateDate:     2018/7/18 16:59
* @UpdateUser:     wangyk
* @UpdateDate:     2018/7/18 16:59
* @UpdateRemark:
* @Version:        1.0
*/
public class InPutExercise
{
    public static void main(String[] args) throws IOException
    {
        downloadBuffer("http://avatar.csdn.net/5/4/C/2_qq_35341771.jpg","F:/picture","mayi.png");
    }
}

2.一個一個位元組下載 

    /**
     * @Description 下載圖片
     * @author      wangyk
     * @param urlPath 圖片在的路徑
     * @param filePath 圖片下載後儲存的資料夾
     * @param fileName 圖片下載後儲存的檔名
     * @return      void
     * @exception
     * @date        2018/7/18 17:06
     */
    public static void download(String urlPath,String filePath,String fileName) throws IOException
    {
        //MalformedURLException:畸形的URL
        URL url= new URL(urlPath);
        //取得連線,IOException
        URLConnection con = url.openConnection();
        //設定超時時間
        con.setConnectTimeout(10*1000);
        //取得檔案的輸入位元組流
        InputStream in= con.getInputStream();
        //獲得資料夾物件
        File file=new File(filePath);
        //判斷資料夾是否存在
        if(!file.exists())
        {
            //資料夾不存在則建立資料夾
            file.mkdirs();
        }
        //檔案的輸出流,沒有此檔案預設直接建立
        OutputStream out=new FileOutputStream(filePath+File.separator+fileName);
        //將檔案一個一個位元組地讀取出來,放在read裡面,當返回-1時,說明檔案讀至末尾
        int read;
        while ((read=in.read())!=-1)
        {
            //將read寫入輸出流
            out.write(read);
        }
        //最後關閉輸入輸出流
        out.close();
        in.close();
    }

3.緩衝位元組下載

/**
     * @Description 使用緩衝流下載圖片
     * @author      wangyk
     * @param urlPath
     * @param filePath
     * @param fileName
     * @return      void
     * @exception
     * @date        2018/7/18 17:11
     */
    public static void downloadBuffer(String urlPath,String filePath,String fileName) throws IOException
    {
        //MalformedURLException:畸形的URL
        URL url= new URL(urlPath);
        //取得連線,IOException
        URLConnection con = url.openConnection();
        //設定超時時間
        con.setConnectTimeout(10*1000);
        //取得檔案的輸入位元組流
        InputStream in= con.getInputStream();
        //獲得資料夾物件
        File file=new File(filePath);
        //判斷資料夾是否存在
        if(!file.exists())
        {
            //資料夾不存在則建立資料夾
            file.mkdirs();
        }
        //檔案的輸出流,沒有此檔案預設直接建立
        OutputStream out=new FileOutputStream(filePath+File.separator+fileName);
        //將檔案一個一個位元組地讀取出來,放在read裡面,當返回-1時,說明檔案讀至末尾
        int read;
        //設定緩衝512位元組
        byte[] buff=new byte[512];
        while ((read=in.read(buff))!=-1)
        {
            //將read寫入輸出流
            out.write(buff,0,buff.length);
        }
        //最後關閉輸入輸出流
        out.close();
        in.close();
    }