日期:2014-05-20  浏览次数:21056 次

java多线程下载文件奇怪问题
public   class   DownFileSpliter   extends   Thread   {
String   dlURL;
long   startPos;
long   endPos;
int   threadID;
boolean   done   =   false;
public   boolean   stop   =   false;
RandomAccessFile   file;
public   DownFileSpliter(String   dlURL,   String   saveAs,   long   nStart,
long   nEnd,   int   id)   throws   IOException   {
this.dlURL   =   dlURL;
this.startPos   =   nStart;
this.endPos   =   nEnd;
this.threadID   =   id;
file   =   new   RandomAccessFile(saveAs,   "rw ");
file.seek(startPos);
}

public   void   run()   {
try   {
long   start   =   System.currentTimeMillis();
URL   url   =   new   URL(dlURL);
HttpURLConnection   httpConnection   =   (HttpURLConnection)   url
.openConnection();
String   sProperty   =   "bytes= "   +   startPos   +   "- ";
httpConnection.setRequestProperty( "RANGE ",   sProperty);
httpConnection.setRequestProperty( "Accept ", "image/gif,image/x-xbitmap,application/msword,*/* ");
System.out.println( "线程 "   +   threadID   +   "下载文件、、、请等待 ");
InputStream   input   =   httpConnection.getInputStream();
byte[]   buf   =   new   byte[1024];
int   offset;
offset   =   (int)   endPos   -   (int)   startPos;
if   (offset   >   1024)
offset   =   1024;
BufferedInputStream   bis   =   new   BufferedInputStream(httpConnection.getInputStream());
while   (bis.read(buf,0,offset)   >   0   &&   startPos   <   endPos)//   循环获取文件
{
offset   =   (int)   endPos   -   (int)   startPos;
if(offset> 1024)
offset   =   1024;
// System.out.println( "threadID:   "   +   threadID   +   "   started:   "+   startPos   +   "     offset:   "   +   offset);
//Thread.sleep(2000);
file.write(buf,   0,   offset);
if(stop){
System.out.println( "线程: "+threadID+ ",被强制中止 ");
break;
}
startPos   +=   offset;
}
System.out.println( "线程 "   +   threadID   +   "执行完毕!! ");
System.out.println( "线程 "+threadID+ ",共用时: "   +   String.valueOf(System.currentTimeMillis()   -   start));
file.close();
input.close();
done   =   true;
}   catch   (Exception   ex)   {
ex.printStackTrace();
}

}
}

用以上线程下载网络文件,可以正常运行,而且下载下来的大小与用下载工具下载下来的内容大小一样,但是用以上程序下载时不能打开,而用工具下载的却可以打开。
特向高手请教关于多线程下载网络文件,请帮忙看看,以上程序出错在哪里,谢谢。

------解决方案--------------------
感觉好像没问题啊。等待高手解答,学习。
------解决方案--------------------
头疼

------解决方案--------------------
我也头疼~
继续顶
------解决方案--------------------