📄 downloadfilethread.java
字号:
package coursedesign;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class DownLoadFileThread extends Thread {
// 网络地址
private String URL;
// 线程下载开始点
private long startPos;
// 线程下载结束点
private long endPos;
private DownLoadFile down;
private RandomAccessFile file;
// 已下载量
private int readPos = 0;
// 下载分量
private int in = 0;
// 构造器
public DownLoadFileThread(String URL, long startPos, long endPos,
String saveURL, DownLoadFile down) throws IOException {
this.URL = URL;
this.startPos = startPos;
this.endPos = endPos;
this.down = down;
file = new RandomAccessFile(saveURL, "rw");
file.seek(startPos);
}
public void run() {
try {
URL url = new URL(URL);
URLConnection httpConnection = url.openConnection();
String sProperty = "bytes=" + startPos + "-";
httpConnection.setRequestProperty("RANGE", sProperty);
InputStream input = httpConnection.getInputStream();
byte[] buf = new byte[1024];
int offset;
offset = (int) endPos - (int) startPos;
if (offset > 1024)
offset = 1024;
while (down.getStatus() == 0 && startPos < endPos
&& (in = input.read(buf, 0, offset)) > 0) {
if (((int) endPos - (int) startPos) < 1024)
in = (int) endPos - (int) startPos;
readPos += in;
offset = (int) endPos - (int) startPos;
if (offset > 1024)
offset = 1024;
file.write(buf, 0, in);
startPos += in;
if (in == -1)
break;
}
file.close();
input.close();
} catch (Exception ex) {
}
}
public int getReadPos() {
return readPos;
}
public void setReadPos(int readPos) {
this.readPos = readPos;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -