FileOutputStream之断点续传

来源:互联网 发布:openstack 数据库服务 编辑:程序博客网 时间:2024/06/16 12:48

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

断点续传的实现方式有多种,在我的探索中,发现了这样一个很好用的东西,那就是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() {@Overridepublic 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);}@Overridepublic boolean isProgress() {return super.isProgress();}@Overridepublic 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
原创粉丝点击