Java断点续传(简单实现)

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");
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值