我写了一个多线程下载,下载本地文件可以,但是下载网上的文件就不行了。不知道哪里有问题,请大侠们指教?下面是程序的核心部分:
public synchronized void run() {
try {
while (true) {
informTextArea.append("线程" + threadId + " 第" + tryConnect+ "次尝试连接\n");//threadId:线程的编号;tryConnect:该线程连接的次数
informTextArea.append("线程" + threadId + " " + startPos + "-"+ endPos + "开始下载" + "\n");//startPos/end:该线程下载文件的开始/结束位置
url = new URL(netAddress);
httpConnection = (HttpURLConnection) url.openConnection();
sProperty = "bytes=" + startPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);//设置线程下载开始位置
if (httpConnection.getResponseCode() < 400) {
input = new BufferedInputStream(httpConnection.getInputStream(), size);
RandomAccessFile fileout = new RandomAccessFile(newFile,"rw");
fileout.seek(startPos);//设置文件指针位置
offset = (int) (endPos - startPos);
if (offset > size)//size=1024
offset = size;
while (input.read(b, 0, offset) != -1 && startPos < endPos) { offset = (int) (endPos - startPos);
if (offset > size) {
offset = size;
}
fileout.write(b,0,offset);//写数据
jProbar.setValue(jProbar.getValue()+offset);
startPos=startPos+offset;
}
done = true;
fileout.close();
input.close();
break;
}
tryConnect++;
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public synchronized void run() {
try {
while (true) {
informTextArea.append("线程" + threadId + " 第" + tryConnect+ "次尝试连接\n");//threadId:线程的编号;tryConnect:该线程连接的次数
informTextArea.append("线程" + threadId + " " + startPos + "-"+ endPos + "开始下载" + "\n");//startPos/end:该线程下载文件的开始/结束位置
url = new URL(netAddress);
httpConnection = (HttpURLConnection) url.openConnection();
sProperty = "bytes=" + startPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);//设置线程下载开始位置
if (httpConnection.getResponseCode() < 400) {
input = new BufferedInputStream(httpConnection.getInputStream(), size);
RandomAccessFile fileout = new RandomAccessFile(newFile,"rw");
fileout.seek(startPos);//设置文件指针位置
offset = (int) (endPos - startPos);
if (offset > size)//size=1024
offset = size;
while (input.read(b, 0, offset) != -1 && startPos < endPos) { offset = (int) (endPos - startPos);
if (offset > size) {
offset = size;
}
fileout.write(b,0,offset);//写数据
jProbar.setValue(jProbar.getValue()+offset);
startPos=startPos+offset;
}
done = true;
fileout.close();
input.close();
break;
}
tryConnect++;
} } catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
会不会是 URL 写得不对呢?