檔案長度" + fileLength);
size = fileLength / threadCount;
System.out.println("每個下載下傳量==" + size);
conn.disconnect();// 斷開連結
}
public URL getFileUrl() {
return fileUrl;
public int getThreadCount() {
return this.threadCount;
/**
* 開始下載下傳
*/
public void startDown() {
for (int i = 0; i < threadCount; i++) {
try {
RandomAccessFile raFile = new RandomAccessFile(pathName, "rw");
tDownthreads[i] = new Downthread(i * size, raFile, i);
tDownthreads[i].start();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
* 下載下傳線程類
*
* @author luweicheng
class Downthread extends Thread {
private int startPos;// 開始的位置
private InputStream is;
private RandomAccessFile raFile;
private int length;// 下載下傳的檔案長度
private int flag;// 線程标志
public Downthread(int startPos, RandomAccessFile raFile, int i) {
this.startPos = startPos;
this.raFile = raFile;
flag = i;
@Override
public void run() {
HttpURLConnection connection = (HttpURLConnection) fileUrl.openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("connection", "keep-alive");
connection.setConnectTimeout(5 * 1000);
is = connection.getInputStream();
is.skip(startPos);
raFile.seek(startPos);
byte[] buf = new byte[8 * 1024];
int hasread = 0;// 讀出的位元組數
// 将位置在 startPos - startPos 位置的資料讀出寫入
while (length < size && (hasread = is.read(buf)) != -1) {
raFile.write(buf, 0, hasread);
length += hasread;
System.out.println("*****線程" + flag + "下載下傳了*********" + length);
}
System.out.println("*******線程" + flag + "下載下傳完成*********");
} catch (IOException e) {
} finally {
try {
is.close();
raFile.close();
} catch (IOException e) {
e.printStackTrace();
}
效果展示:
