1. 程式人生 > >JAVA 如何一次下載多個檔案

JAVA 如何一次下載多個檔案

https://zhidao.baidu.com/question/1446055057527183940.html

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Vector;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
/**
 * 本例使用的是基於JDK HttpURLConnection的同步下載,即按順序下載
 * 如果同時下載多個任務,可以使用多執行緒
 * @author aK1ng
 *
 */
public class Demo1 {
    public static void main(String[] args) {
        // 下載列表
        Vector<String> downloadList = new Vector<String>();
        // 新增下載地址
        downloadList.add("
);
        downloadList.add("
);
        download(downloadList);
    }
     
    /**
     * 下載
     */
    static void download(Vector<String> downloadList){
        // 執行緒池
        ExecutorService pool = null;
        HttpURLConnection connection = null;
        //迴圈下載
        try {
            for (int i = 0; i < downloadList.size(); i++) {
                pool = Executors.newCachedThreadPool();
                final String url = downloadList.get(i);
                String filename = getFilename(downloadList.get(i));
                System.out.println("正在下載第" + (i+1) + "個檔案,地址:" + url);
                Future<HttpURLConnection> future = pool.submit(new Callable<HttpURLConnection>(){
                    @Override
                    public HttpURLConnection call() throws Exception {
                        HttpURLConnection connection = null;
                        connection = (HttpURLConnection) new URL(url).openConnection(); 
                        connection.setConnectTimeout(10000);//連線超時時間
                        connection.setReadTimeout(10000);// 讀取超時時間
                        connection.setDoInput(true);
                        connection.setDoOutput(true);
                        connection.setRequestMethod("GET");
                        //斷點續連,每次要算出range的範圍,請參考Http 1.1協議
                        //connection.setRequestProperty("Range", "bytes=0");
                        connection.connect();
                        return connection;
                    }
                });
                connection = future.get();
                System.out.println("下載完成.響應碼:"+ connection.getResponseCode());
                // 寫入檔案
                writeFile(new BufferedInputStream(connection.getInputStream()), URLDecoder.decode(filename,"UTF-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != connection)
                connection.disconnect();
            if (null != pool) 
                pool.shutdown();
        }
    }
     
    /**
     * 通過擷取URL地址獲得檔名
     * 注意:還有一種下載地址是沒有檔案字尾的,這個需要通過響應頭中的
     * Content-Disposition欄位 獲得filename,一般格式為:"attachment; filename=\xxx.exe\"
     * @param url
     * @return
     */
    static String getFilename(String url){
        return ("".equals(url) || null == url) ? "" : url.substring(url.lastIndexOf("/") + 1,url.length());
    }
     
    /**
     * 寫入檔案
     * @param inputStream
     */
    static void writeFile(BufferedInputStream bufferedInputStream,String filename){
        //建立本地檔案
        File destfileFile = new File("d:\\temp\\download\\"+ filename);
        if (destfileFile.exists()) {
            destfileFile.delete();
        }
        if (!destfileFile.getParentFile().exists()) {
            destfileFile.getParentFile().mkdir();
        }
        FileOutputStream fileOutputStream = null;
        try {
            fileOutputStream = new FileOutputStream(destfileFile);
            byte[] b = new byte[1024];
            int len = 0;
            // 寫入檔案
            System.out.println("開始寫入本地檔案.");
            while ((len = bufferedInputStream.read(b, 0, b.length)) != -1) {
                System.out.println("正在寫入位元組:" + len);
                fileOutputStream.write(b, 0, len);
            }
            System.out.println("寫入本地檔案完成.");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fileOutputStream) {
                    fileOutputStream.flush();
                    fileOutputStream.close();
                }
                if (null != bufferedInputStream)
                    bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}