沈君 2017-01-14 08:56 采纳率: 0%
浏览 1239

写了个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条回答

  • threenewbee 2017-01-14 16:03
    关注
    评论

报告相同问题?

悬赏问题

  • ¥60 更换迈创SOL6M4AE卡的时候,驱动要重新装才能使用,怎么解决?
  • ¥15 让node服务器有自动加载文件的功能
  • ¥15 jmeter脚本回放有的是对的有的是错的
  • ¥15 r语言蛋白组学相关问题
  • ¥15 Python时间序列如何拟合疏系数模型
  • ¥15 求学软件的前人们指明方向🥺
  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题