public class BreakPointDownLoad {
private int bufferSize = 32;
public void URLLoad(String sourceUrl, String fileName) {
InputStream input = null;
RandomAccessFile access = null;
try {
// 获取资源
URL url = new URL(sourceUrl);
input = url.openStream();
// 初始化存储文件
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
// 资源长度
long sourceSize = url.openConnection().getContentLength();
// 存储文件长度
long fileSize = file.length();
long pointSize = 0;
// 判断是否已下载完成
if (sourceSize > fileSize) {
// 断点下载
pointSize = fileSize;
} else {
// 重新下载
file.delete();
file.createNewFile();
}
access = new RandomAccessFile(file, "rw");
// 资源,文件定位
input.skip(pointSize);
access.seek(pointSize);
byte[] buffer = new byte[bufferSize];
int count = 0;
System.out.println("正在下载...");
while ((count = input.read(buffer)) != -1) {
access.write(buffer, 0, count);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
input.close();
access.close();
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("下载完成");
}
public static void main(String[] args) {
BreakPointDownLoad load = new BreakPointDownLoad();
load.URLLoad("http://www.baidu.com/", "D:/juhua.html");
}
}