FileOutputStream之断点续传

相信做安卓开发的都会遇到断点续传的这样一个问题。

断点续传的实现方式有多种,在我的探索中,发现了这样一个很好用的东西,那就是FileOutputStream。我简直大吃一惊!这玩意可以实现断点续传?!(断点续传额!不是简单的下载,暂停,再继续下载,就算是你把程序杀死了,下次会继续原来的下载地方继续下载)不错!就是这样的。首先我们来看下FileOutputStream这个方法。

<span style="font-size:18px;">public FileOutputStream(File file,boolean append) throwsFileNotFoundException</span>

API里是这样解释的:

Creates a file output stream to write to the file represented by the specified File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning. A new FileDescriptor object is created to represent this file connection.

大致的意思是以流追加的方式实现文件的追加,而不是覆盖之前的文件。How?又一个新的玩意映入眼帘。FileDescriptor,这个东西可以将一种file connection保存到下载的文件中。API说明如下:

<span style="font-size:18px;">Instances of the file descriptor class serve as an opaque handle to the underlying machine-specific structure representing an open file, an open socket, or another source or sink of bytes. The main practical use for a file descriptor is to create a FileInputStream or FileOutputStream to contain it.Applications should not create their own file descriptors.</span>

大致的意思是这个东西不单单可以实现an open file的文件追加,还可以是an open socket。这个就厉害了。可以实现网络请求的断点续传。至于底层是如何实现的,就不做深究了。感谢大神杨福海的afinal。一个方法实现文件断点续传下载,原理就是FileOutputStream(File file,boolean append)这个方法。

其实,还有个断点续传的方法,RandomAccessFile(有待探究)

安卓核心代码:

			callBack = new AjaxCallBack() {
				@Override
				public void onLoading(long count, long current) {
					textView.setText("下载进度:" + (current / 1024) + "K" + "/"
							+ (count / 1024) + "K");
					progress2 = (int) (current / (float) count * 100);
					System.out.println(progress2);
					message = handler.obtainMessage();
					message.arg1 = progress2;
					handler.sendMessage(message);
				}
				@Override
				public boolean isProgress() {
					return super.isProgress();
				}
				@Override
				public void onSuccess(Object t) {
					if (t instanceof File) {
						File f = (File) t;

						textView.setText(f == null ? "null" : f
								.getAbsoluteFile().toString());
					}
				}
			};
			httpHandler = fh.download("http://idong.co/joy/runner.apk",
					new AjaxParams(), AppUtils.getMyCacheDir("")
							+ "testapk.apk", true, callBack);
想要看具体实现的,去看gitHub上的afinal。






  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JsonEric

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值