Java tutorial
/* * Copyright (c) 2014,KJFrameForAndroid Open Source Project,. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.louding.frame.http.download; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.RandomAccessFile; import org.apache.http.HttpEntity; import com.louding.frame.http.download.SimpleDownloader.DownloadProgress; import com.louding.frame.utils.FileUtils; public class FileEntityHandler { private boolean mStop = false; public boolean isStop() { return mStop; } public void setStop(boolean stop) { this.mStop = stop; } public File handleEntity(HttpEntity entity, DownloadProgress callback, File save, boolean isResume) throws IOException { long current = 0; RandomAccessFile file = new RandomAccessFile(save, "rw"); if (isResume) { current = file.length(); } InputStream input = entity.getContent(); long count = entity.getContentLength() + current; if (mStop) { FileUtils.closeIO(file); return save; } // ??????? /** * <br> * current = input.skip(current); <br> * file.seek(current); <br> * ?JDKInputstream.skip(long i)i<br> * ? n ??????? */ file.seek(input.skip(current)); int readLen = 0; byte[] buffer = new byte[1024]; while ((readLen = input.read(buffer, 0, 1024)) != -1) { if (mStop) { break; } else { file.write(buffer, 0, readLen); current += readLen; callback.onProgress(count, current); } } callback.onProgress(count, current); if (mStop && current < count) { // ? FileUtils.closeIO(file); throw new IOException("user stop download thread"); } FileUtils.closeIO(file); return save; } }