Java断点续传(简单实现)

来源:互联网 发布:mysql 最近10天 编辑:程序博客网 时间:2024/06/09 06:33
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");}}


原创粉丝点击