最近闲来无事,所以写了一个java的下载模块,稍微修改了一下弄成了无限下载。
首先是线程类:
package com.gzh.test;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
public class DownloadThread extends Thread {
private String url = null;
private String file = null;
private long offset = 0;
private long length = 0;
public DownloadThread(String url, String file, long offset, long length) {
this.url = url;
this.file = file;
this.offset = offset;
this.length = length;
}
@Override
public void run() {
try {
HttpURLConnection conn = (HttpURLConnection) new URL(url)
.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("RANGE", "bytes=" + this.offset + "-"
+ (this.offset + this.length - 1));
BufferedInputStream bis = new BufferedInputStream(
conn.getInputStream());
byte[] buf = new byte[1024];
int bytesRead;
while ((bytesRead = bis.read(buf, 0, buf.length)) != -1) {
this.writeFile(file, offset, buf, bytesRead);
this.offset += bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
}
}
public void writeFile(String fileName, long offset, byte[] bytes,
int realLength) throws IOException {
File file = new File(fileName);
RandomAccessFile raf = new RandomAccessFile(file, "rw");
raf.seek(offset);
raf.write(bytes, 0, realLength);
raf.close();
}
}
然后随便写一个类实现main():
while循环是个死循环,每隔10秒运行一次线程。
package com.gzh.test;
import java.io.File;
public class Main {
public static void main(String[] args) {
String url = "http://d2.eoemarket.com/upload/apps/2013/0607/148237/apks/07c73b70-9cbf-4a7f-eeb7-1f8b35e24cd1.apk";
int a = 0;
while (true) {
String file = "D:\\javaTest\\" + System.currentTimeMillis()
+ ".apk";
long offset = 0;
long length = 0;
new DownloadThread(url, file, offset, length).start();
try {
Thread.sleep(15000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(a++);
}
}
}
灰常无聊啊,只是希望初学者能够掌握简单的java单线程下载。最后推荐一款IT学习软件“IT视频排行榜”,绿色健康小清新呦,地址→http://www.eoemarket.com/soft/148237.html