您的位置:首页 > 其它

文件下载工具类

2016-12-23 15:04 323 查看
import android.os.AsyncTask;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

public class MyDownAsync extends AsyncTask<String,Integer,byte[]> {

private File file;
private FreedomCallback freedomCallback;

public MyDownAsync(File file,FreedomCallback freedomCallback) {
this.file = file;
this.freedomCallback=freedomCallback;
}

@Override
protected byte[] doInBackground(String... params) {
if(params[0]!=null){
saveFileFromURL(params[0],file);
}
return null;
}

@Override
protected void onPostExecute( byte[] result) {
freedomCallback.finished(result);
super.onPostExecute(result);
}

public static boolean saveFileFromURL(String url, File destFile) {
HttpURLConnection httpConn = null;
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(new FileOutputStream(destFile));
URL urlObj = new URL(url);
httpConn = (HttpURLConnection) urlObj.openConnection();
httpConn.setRequestMethod("GET");
httpConn.setDoInput(true);
httpConn.setConnectTimeout(100000);
httpConn.connect();

if (httpConn.getResponseCode() == 200) {
bis = new BufferedInputStream(httpConn.getInputStream());
int c = 0;
byte[] buffer = new byte[8 * 1024];
while ((c = bis.read(buffer)) != -1) {
bos.write(buffer, 0, c);
bos.flush();
}
}
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bis != null) {
bis.close();
}
if (bos != null) {
bos.close();
}
httpConn.disconnect();
} catch (IOException e) {
e.printStackTrace();
}
}
return false;
}
public interface FreedomCallback {
void finished(byte[] result);
}

}

File file=new File(mDownloadDir+"/"+"hello.js");
new MyDownAsync(file, new MyDownAsync.FreedomCallback() {
@Override
public void finished(byte[] result) {

}
}).execute(url);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: