/**
*
* @author yw04009 Bill, Wu
*
*/
public class TestDownLoad {
public void testOneThread(String filePath, String url) throws IOException {
File file = new File(filePath + getFileExtName(url));
FileWriter fWriter = new FileWriter(file);
URL ul = new URL(url);
URLConnection conn = ul.openConnection();
conn.setConnectTimeout(2000);
InputStream in = conn.getInputStream();
int temp = 0;
while ((temp = in.read()) != -1) {
fWriter.write(temp);
}
fWriter.close();
in.close();
}
public String getFileExtName(String path) {
return path.substring(path.lastIndexOf("."));
}
public void testMoreThread(String filePath, String url, int tnum) throws IOException {
final File file = new File(filePath + getFileExtName(url));
RandomAccessFile accessFile = new RandomAccessFile(file, "rwd");
final URL ul = new URL(url);
HttpURLConnection conn = (HttpURLConnection) ul.openConnection();
conn.setConnectTimeout(2000);
conn.setRequestMethod("GET");
int len = conn.getContentLength();
accessFile.setLength(len);
accessFile.close();
final int block = (len + tnum - 1) / tnum; //the size for every thread download
for (int i = 0; i < tnum; i++) {
final int a = i;
new Thread(new Runnable() {
int start = block * a; //start place
int end = block * (a + 1) - 1; //end place
public void run() {
// TODO Auto-generated method stub
HttpURLConnection conn2 = null;
RandomAccessFile accessFile2 = null;
InputStream in = null;
try {
conn2 = (HttpURLConnection) ul.openConnection();
conn2.setConnectTimeout(2000);
conn2.setRequestMethod("GET");
conn2.setRequestProperty("Range", "bytes=" + start
+ "-" + end + "");//
in = conn2.getInputStream();
byte[] data = new byte[1024];
int len = 0;
accessFile2 = new RandomAccessFile(file, "rwd");
accessFile2.seek(start);
while ((len = in.read(data)) != -1) {
accessFile2.write(data, 0, len);
}
System.out.println("This Thread Download is Compled .. ");
} catch (IOException e) {
}
}
}).start();
}
}
public static void main(String[] args) throws IOException {
TestDownLoad test = new TestDownLoad();
String path = "http://bill.com/test.txt";
//test.testOneThread("C:\\code\\test1", path);
//test.testMoreThread("C:\\code\\test2", path, 3); }
}
本文介绍了一种使用多线程技术实现文件下载的方法。通过将文件分成多个部分并为每一部分分配一个独立的线程进行下载,可以显著提高下载速度。文章提供了具体的Java代码示例,展示了如何创建多线程下载任务以及如何处理HTTP请求。

7944

被折叠的 条评论
为什么被折叠?



