task.java
来自「这是一个支持续传的下载程序」· Java 代码 · 共 144 行
JAVA
144 行
public class Task {
private String downURL;
private String saveFile;
private int bufferSize = 64 * 1024;
private int workerCount;
private int sectionCount;
private long contentLength;
private long[] sectionsOffset;
public static final int HEAD_SIZE = 4096;
//读下载描述文件内容
public synchronized void read(RandomAccessFile file) throws IOException {
byte[] temp = new byte[HEAD_SIZE];
file.seek(0);
int readed = file.read(temp);
if (readed != temp.length) {
throw new RuntimeException();
}
ByteArrayInputStream bais = new ByteArrayInputStream(temp);
DataInputStream dis = new DataInputStream(bais);
downURL = dis.readUTF();
saveFile = dis.readUTF();
sectionCount = dis.readInt();
contentLength = dis.readLong();
sectionsOffset = new long[sectionCount];
for (int i = 0; i < sectionCount; i++) {
sectionsOffset[i] = file.readLong();
}
}
//创建下载描述文件内容
public synchronized void create(RandomAccessFile file) throws IOException {
if (sectionCount != sectionsOffset.length) {
throw new RuntimeException();
}
long len = HEAD_SIZE + 8 * sectionCount;
file.setLength(len);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
dos.writeUTF(downURL);
dos.writeUTF(saveFile);
dos.writeInt(sectionCount);
dos.writeLong(contentLength);
byte[] src = baos.toByteArray();
byte[] temp = new byte[HEAD_SIZE];
System.arraycopy(src, 0, temp, 0, src.length);
file.seek(0);
file.write(temp);
writeOffset(file);
}
//更新下载的过程
public synchronized void writeOffset(RandomAccessFile file) throws IOException {
if (sectionCount != sectionsOffset.length) {
throw new RuntimeException();
}
file.seek(HEAD_SIZE);
for (int i = 0; i < sectionsOffset.length; i++) {
file.writeLong(sectionsOffset[i]);
}
}
(下面是Getter、Setter)
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?