java+线程+debug_急:写了个JAVA多线程下载的代码,调试过了,运行就空指针异常,高手指...

该楼层疑似违规已被系统折叠 隐藏此楼查看此楼

import java.io.*;

import java.net.*;

import java.util.*;

public class MyThread extends Thread{

private static String defaultsave="D:\\";//默认保存路径

private File ft;//临时文件

private InputStream is;

private int threadNum;//线程数

private long[] startPos;//开始位置

private long[] endPos;//结束位置

private long filelength;//文件长度

//boolean bFirst=true;//是否第一次取文件

private int i;//第i个线程

String filename;

String spec;

public static void main(String[] args){

MyThread my=new MyThread();

my.testThread();

}

public void testThread(){

try{

spec="http://image2.sina.com.cn/gm/o/i/2007-02-15/U1237P115T41D118013F757DT20070215165442.jpg";

URL url=new URL(spec);

Properties prop = System.getProperties();

prop.put("http.proxyHost","172.16.0.10");

prop.put("http.proxyPort","11080");

int in=spec.lastIndexOf("/");

filename=spec.substring(in+1);

File f=new File(defaultsave+filename);

URLConnection uc=url.openConnection();

is=url.openStream();

filelength=uc.getContentLength();

//按指定线程数分割文件,新建线程开始下载

threadNum=3;

startPos=new long[threadNum];

endPos=new long[threadNum];

long threadLength=filelength/threadNum;

for(i=0;i

startPos[i]=threadLength*i+1;

endPos[i]=threadLength;

endPos[threadNum-1]=filelength-threadLength*(threadNum-1);

System.out.println("第"+i+"线程从第"+startPos[i]+"个字节开始读取"+endPos[i]+"个字节");

MyThread[] mt=new MyThread[threadNum];

mt[i]=new MyThread();

mt[i].start();

}

}catch(Exception e){

e.printStackTrace();

}

}

public void run(){

try{

ft=new File(defaultsave+filename+i);

is.skip(startPos[i]-1);

FileOutputStream fos=new FileOutputStream(ft);

BufferedOutputStream bos=new BufferedOutputStream(fos);

int tmp=0;

int count=0;

while((tmp=is.read())!=-1){

bos.write(tmp);

count++;

if(count>=endPos[i]+1){

break;

}

}

bos.close();

fos.close();

//fis.close();

is.close();

System.out.println("下载结束,请在"+defaultsave+"查看");

}catch(Exception e){

e.printStackTrace();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值