使用多線程下載文件

import java.io.File;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;

public class MultiThreadDownloadFile {


public static String getFileName(String path)
{

return path.substring(path.lastIndexOf("/")+1);

}
public static void downloadFile (String path, int threadSize)throws Exception
{
URL url = new URL(path);

HttpURLConnection connection = (HttpURLConnection)url.openConnection();
 
connection.setRequestMethod("GET");
//connection.setConnectTimeout(5*1000);
int fileLength = connection.getContentLength(); // 獲取文件的長度
String decodePath =  java.net.URLDecoder.decode(path, "UTF-8");  
File saveFile = new File("F:\\"+getFileName(decodePath ));

RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.setLength(fileLength); //開始的時候就設定好要寫入的文件的大小
accessFile.close();
int block = 0;                                                // 記錄每個線程下載文件的大小
if((fileLength / threadSize) == 0)
{
block = fileLength / threadSize;
}
else
{
block = fileLength / threadSize + 1;
}
for(int threadID = 0; threadID < threadSize; threadID ++)
{
new DownloadThread(url,saveFile,block,threadID).start();
}
}
private static final class DownloadThread extends Thread
{
private URL url;
private File saveFile;
private int block;
private int threadID;

public DownloadThread(URL url, File saveFile, int block, int threadID) {
this.block = block;
this.saveFile = saveFile;
this.threadID = threadID;
this.url = url;
}


@Override
public void run() {
int startPosition = threadID * block;
int endPosition = (threadID + 1) * block - 1;
HttpURLConnection connection = null;
try 
{
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startPosition); // 設置從什麼位置開始寫入數據
connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
//connection.setConnectTimeout(5*1000);
connection.setRequestProperty("Range", "bytes="+startPosition+"-"+endPosition);// 指定從網絡文件的開始位置到結束位置下載。
InputStream inputStream = connection.getInputStream();
byte [] buffer = new byte[1024];
int length = 0;
while((length = inputStream.read(buffer)) != -1)
{
accessFile.write(buffer,0,length);
}
inputStream.close();
accessFile.close();
System.out.println("線程id:"+threadID+"下載完成");

catch (Exception e) 
{
// TODO Auto-generated catch block
e.printStackTrace();
}

}


}
/**
* @param args
*/
public static void main(String[] args) {

String path = "http://file17.top100.cn/201109041608/5B18BF2F7767FE72F221F1182775682F/Special_344867"+

"/%E5%9B%A0%E4%B8%BA%E7%88%B1%E6%83%85.mp3";         // 目前我還不清楚怎麼把%E5%9B%A0%E4%B8%BA%E7%88%B1%E6%83%85.mp3轉換成中文,這首歌名是"因爲愛情.mp3"。這個問題已解決,請看紅色部分。

try 
{
MultiThreadDownloadFile.downloadFile(path, 3);

catch (Exception e) 
{
// TODO Auto-generated catch block
e.printStackTrace();
}


}


}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章