当前位置:首页 » JAVA技术教程

Java多线程下载

2011-08-24 02:58 本站整理 浏览(14)

理想模式代码.仅作参考之用

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyThreadDownloader
{
    public static void main(String args[])
    {
        // 下载连接
        String downloadURL = "http://localhost:8080/cangjingkong.avi";
        // 下载开启线程数
        int threadSize = 3;
        try
        {
            new MyThreadDownloader().download(downloadURL, threadSize);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    private void download(String downloadURL, int threadSize) throws Exception
    {
        String fileName = getFileName(downloadURL);

        URL url = new URL(downloadURL);

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        // 设置超时
        connection.setConnectTimeout(5000);
        // 设置请求方式
        connection.setRequestMethod("GET");
        // 获取文件长度
        int fileLength = connection.getContentLength();
        // 保存文件
        File localFile = new File(fileName);
        // 临时文件不存内存,直接进行数据读写"rwd"
        RandomAccessFile randomAccessFile = new RandomAccessFile(localFile,"rwd");
        // 直接创建与服务器获取长度相等的文件
        randomAccessFile.setLength(fileLength);
        // 文件操作over,关闭
        randomAccessFile.close();

        // 计算每条线程负责下载的数据量
        int downblock = fileLength % threadSize == 0 ? fileLength / threadSize
                : fileLength / threadSize + 1;
        // 分配每条线程下载任务
        for (int threadID = 0; threadID < threadSize; threadID++)
        {
            //开启多线程下载任务
            new DownloadThread(threadID, url, localFile, downblock).start();
        }
    }

    /**
     * @param downloadURL
     *            下载连接
     * @return 返回下载文件名
     */
    private String getFileName(String downloadURL)
    {
        return downloadURL.substring(downloadURL.lastIndexOf("/") + 1);
    }

    public final class DownloadThread extends Thread
    {
        private int threadID;      // 当前下载线程ID
        private URL url;           // 下载连接
        private File localFile;    // 目标文件
        private int downblock;     // 分段下载长度
        private int startPosition; // 开始下载位置
        private int endPosition;   // 结束下载位置

        public DownloadThread(int threadID, URL url, File localFile,
                int downblock)
        {
            this.threadID = threadID;
            this.url = url;
            this.localFile = localFile;
            this.downblock = downblock;
        }

        public void run()
        {
            startPosition = threadID * downblock;
            endPosition = (threadID + 1) * downblock;
            try
            {
                RandomAccessFile randomAccessFile = new RandomAccessFile(localFile,"rwd");
                randomAccessFile.seek(startPosition);
                
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setReadTimeout(5000);
                connection.setRequestMethod("GET");
                connection.setRequestProperty("Range", "bytes="+startPosition+"-"+endPosition);
                
                InputStream inputStream = connection.getInputStream();
                byte[] buffer = new byte[1024];
                int len = 0;
                while ((len = inputStream.read(buffer)) != -1)
                {
                    randomAccessFile.write(buffer, 0, len);
                }
                
                inputStream.close();
                randomAccessFile.close();
                
                System.out.println("第"+(threadID+1)+"条线程已经下载完成");
                
            }
            catch (FileNotFoundException e)
            {
                e.printStackTrace();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}
未做任何处理