java下載文件到本地磁盤


 

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

import org.apache.log4j.Logger;

import com.talkweb.entity.CustomException;

/**
 * Java原生的API可用於發送HTTP請求,即java.net.URL、java.net.URLConnection,這些API很好用、很常用,
 * 但不夠簡便;
 * 
 * 1.通過統一資源定位器(java.net.URL)獲取連接器(java.net.URLConnection) 2.設置請求的參數 3.發送請求
 * 4.以輸入流的形式獲取返回內容 5.關閉輸入流
 * 
 *
 */
public class HttpConnectionUtil {

    private static Logger logger = Logger.getLogger(HttpConnectionUtil.class);

    /**
     * 
     * @param urlPath     下載路徑
     * @param fileSavePath 下載存放目錄,包含文件名
     * @return 返回下載文件
     * @throws Exception
     */
    public static File downloadFile(String urlPath, String fileSavePath) throws Exception {

        logger.info("進入下載文件工具類");
        File file = null;
        BufferedInputStream bin = null;
        OutputStream out = null;
        try {
            // 統一資源
            URL url = new URL(urlPath);
            // 連接類的父類,抽象類
            URLConnection urlConnection = url.openConnection();
            // http的連接類
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 設定請求的方法,默認是GET
            httpURLConnection.setRequestMethod("GET");
            // 設置字符編碼
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打開到此 URL 引用的資源的通信鏈接(如果尚未建立這樣的連接)。
            httpURLConnection.connect();

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);
            fileFullName = fileFullName.substring(fileFullName.lastIndexOf("/") + 1);
            logger.info("開始下載文件:" + fileFullName);
            logger.info("file length---->" + fileLength);

            url.openConnection();

            bin = new BufferedInputStream(httpURLConnection.getInputStream());

            String path = fileSavePath;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 打印下載百分比
                if ((len * 100 / fileLength)>50&&(len * 100 / fileLength)<55) {
                    logger.info("下載了-------> " + len * 100 / fileLength + "%");
                }else    if ((len * 100 / fileLength)>=98) {
                    logger.info("下載了-------> " + len * 100 / fileLength + "%");
                }
                //logger.info("下載了-------> " + len * 100 / fileLength + "%");
            }
            return file;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            throw new CustomException(e.toString()+"文件下載異常,請檢查下載鏈接$$"+urlPath);
        } finally {
            if (bin!=null) {
                bin.close();
            }
            if (out!=null) {
                out.close();
            }
        }
    }

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM