2 qq1131410679 qq1131410679 于 2017.01.14 16:56 提问

写了个java多线程下载器,但只有文件的部分内容下载成功。求大神!

import java.net.*;
import java.io.*;

class Test {
//定义文件大小
private static int fileLength;
//定义文件保存路径
private static String fileDirection;
//定义线程数量
private static int threadNum;
//定义线程组
private static Threads[] threads;
//定义资源下载路径
private static String webDirection;

/**
 * 默认构造器
 * */
public Test(){}

/**
 * 构造器:
 * 初始化threadNum(线程数量),fileDirection(文件保存路径),webDirection(资源下载路径)
 * */
public Test(int threadNum, String fileDirection, String webDirection) {

    this.threadNum = threadNum;
    this.fileDirection = fileDirection;
    this.webDirection = webDirection;
    //初始化threads数量。
    threads = new Threads[threadNum];
}


public static void downLoad() throws Exception {

    URL url = new URL(webDirection);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("GET");
    conn.setRequestProperty("Accept", "*/*");
    conn.setRequestProperty("Accept",
            "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                    + "application/x-shockwave-flash, application/xaml+xml, "
                    + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                    + "application/x-ms-application, application/vnd.ms-excel, "
                    + "application/vnd.ms-powerpoint, application/msword, */*");
    conn.setRequestProperty("Charset", "UTF-8");

    //获取连接
    conn.connect();
    //输出连接响应代码
    System.out.println(conn.getResponseCode());

    //获得文件大小
    fileLength = conn.getContentLength();
    //关闭连接
    conn.disconnect();

    //设置每条线程下载部分的大小
    int subLength = fileLength / threadNum + 1;

    //设置本地文件的大小
    RandomAccessFile file = new RandomAccessFile(fileDirection, "rw");
    file.setLength(fileLength);
    file.close();

    //以循环的方式来开始每一条线程
    for (int i = 0; i < threadNum; i++) {

        //计算每条线程的下载的开始位置
        int startPoint = i * subLength;

        //每条线程使用一个RandomAccessFile进行下载
        RandomAccessFile subFile = new RandomAccessFile(fileDirection, "rw");
        //定位该线程的下载位置
        subFile.seek(startPoint);

        //初始化该线程
        threads[i] = new Threads(subLength, startPoint, subFile, webDirection);
        //启动线程
        threads[i].start();

    }

}

}

class Threads extends Thread {

//定义该线程的下载位置
private static int startPoint;
//当前线程需要下载的文件块
private static RandomAccessFile subFile;
//定义资源的下载路径
private static String webDirection;
//定义当前线程需要下载的问文件大小
private static int subLength;
//定义已下载文件字节数
private static int length;

/**
 * 构造器:
 * 初始化sublength,startPoint,subFile,webDirection
 * */
public Threads(int sublength, int startPoint, RandomAccessFile subFile, String webDirection) {
    this.startPoint = startPoint;
    this.subLength = sublength;
    this.subFile = subFile;
    this.webDirection = webDirection;

}

@Override 
public void run() {
    try {
        URL url = new URL(webDirection);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");
        conn.setConnectTimeout(1000);
        conn.setRequestProperty("Accept",
                "image/gif, image/jpeg, image/pjpeg, image/pjpeg, "
                        + "application/x-shockwave-flash, application/xaml+xml, "
                        + "application/vnd.ms-xpsdocument, application/x-ms-xbap, "
                        + "application/x-ms-application, application/vnd.ms-excel, "
                        + "application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.connect();

        //获取一个输出流,
        InputStream input = conn.getInputStream();


        //是输出流跳过startpoint字节,表明该线程只下载自己负责的那一部分文件块
        input.skip(startPoint);

        byte[] buffer = new byte[1024];
        int hasNext = 0;
        //读取网络数据,并写入本地文件
        while (length < subLength && (hasNext = input.read(buffer)) != -1) {
            subFile.write(buffer, 0, hasNext);
            //累计该线程的下载的总大小
            length += hasNext;
        }

        input.close();
        subFile.close();

    } catch (Exception e) {

    }

}

}

public class ThreadsDownload {

public static void main(String[] args)throws Exception {
    // TODO Auto-generated method stub
Test test = new Test(2,
            "C:\\Users\\Administrator\\Desktop\\music.txt",
            "http://shcm09.baidupcs.com/file/59980bec5eb499787dc6888f8c769620?bkt=p3-140059980bec5eb499787dc6888f8c769620847e32380000000003bc&fid=2283488641-250528-388951467231009&time=1484371050&sign=FDTAXGERLBH-DCb740ccc5511e5e8fedcff06b081203-%2FRxhx4PSo2A2tg6emD0bGTEM5DQ%3D&to=sh09vb&fm=Nan,B,M,mn&sta_dx=956&sta_cs=5&sta_ft=txt&sta_ct=0&sta_mt=0&fm2=Nanjing02,B,M,mn&newver=1&newfm=1&secfm=1&flow_ver=3&pkey=140059980bec5eb499787dc6888f8c769620847e32380000000003bc&sl=69926991&expires=8h&rt=pr&r=745301334&mlogid=314351329813847523&vuk=2283488641&vbdid=2298463801&fin=test.txt&fn=test.txt&slt=pm&uta=0&rtype=1&iv=0&isw=0&dp-logid=314351329813847523&dp-callid=0.1.1&csl=500&csign=Cfc%2B%2Bn4hgLFC3dLFpSY0MMKwS%2BE%3D");

test.downLoad();

}

2个回答

caozhy
caozhy   Ds   Rxr 2017.01.15 00:03
qq_33750826
qq_33750826   2017.01.16 14:42

你好,你代码太多了,没怎么看,但是我主页有讲解关于多线程的,你可以去看看能不能帮助你

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!