java遠程文件下載,支持文件斷點續傳

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.log4j.Logger;

/**
* 遠程文件下載,支持文件斷點續傳
* @author ketqi
*/
public class FileDownload {
    private Logger logger = Logger.getLogger(FileDownload.class);
    private static final SimpleDateFormat FORMAT = new SimpleDateFormat("yyyyMMddHHmmss");
    // 遠程文件的url
    private URL url;
    // 下載完後的目標臨時文件
    private File tempFile;
    // 失敗次數
    private int count = 0;

    public FileDownload(String url) throws Exception {
        this.url = new URL(url);
        tempFile = File.createTempFile(FORMAT.format(new Date()), ".xml");
    }

    /**
     * @category 支持斷點續傳的受控端下載
     * @param fileLength
     *            讀取遠程文件的開始位置
     * @return
     */
    public void execute(long fileLength) {
        long currentSize = fileLength;
        HttpURLConnection httpConnection = null;
        InputStream input = null;
        RandomAccessFile targetFile = null;
        try {
            httpConnection = (HttpURLConnection) url.openConnection();
            // 設置User-Agent
            httpConnection.setRequestProperty("User-Agent", "NetFox");
            // 設置斷點續傳的開始位置
            httpConnection.setRequestProperty("RANGE", "bytes=" + fileLength + "-");
            // 獲得輸入流
            input = httpConnection.getInputStream();
            targetFile = new RandomAccessFile(tempFile, "rw");
            // 定位文件指針到fileLength位置
            targetFile.seek(fileLength);
            byte[] b = new byte[1024];
            int nRead;
            // 從輸入流中讀入字節流,然後寫到文件中
            while ((nRead = input.read(b, 0, 1024)) > 0) {
                (targetFile).write(b, 0, nRead);
                currentSize += nRead;
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            e.printStackTrace();

            // 60秒鐘的間隔進行再次嘗試連接
            logger.info("等待60秒後再次進行斷點下載");
            try {
                Thread.sleep(60000);
            } catch (Exception e1) {
            }

            // 續傳
            if (currentSize < getRemoteFileSize()) {
                logger.info("在" + currentSize + "續傳");
                //續傳已超過20次放棄下載
                if (count < 20) {
                    execute(currentSize);
                }
            }
        } finally {
            if (targetFile != null) {
                try {
                    targetFile.close();
                } catch (Exception e) {
                }
                targetFile = null;
            }

            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                }
                input = null;
            }
            if(httpConnection != null){
                httpConnection.disconnect();
            }
        }
    }

    /**
     * @category 已下載的文件
     * @return
     */
    public File getFile() {
        return tempFile;
    }

    /**
     * @category 獲得遠程文件大小
     * @return
     */
    public long getRemoteFileSize() {
        long size = 0;
        try {
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            size = conn.getContentLength();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return size;
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章