您的位置:首页 > 其它

使用多线程下载文件

2011-09-04 16:32 302 查看
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();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: