新增BT下载器

This commit is contained in:
yutou
2021-04-07 18:31:35 +08:00
parent 5d5a4eef97
commit 778f37ed4c
11 changed files with 276 additions and 12 deletions

View File

@@ -1,12 +1,10 @@
package com.yutou.nas.utils;
import com.alibaba.fastjson.JSONObject;
import com.yutou.nas.interfaces.DownloadInterface;
import com.yutou.nas.utils.Interfaces.NetworkInterface;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
@@ -129,4 +127,60 @@ public class HttpTools {
System.out.println(url);
//String str=get(url);
}
private static String donwloadPath="tmp"+File.separator;
public synchronized static void download(final String url, final String saveName, final DownloadInterface downloadInterface) {
new Thread(new Runnable() {
@Override
public void run() {
File jar = null;
try {
File savePath = new File(donwloadPath);
if (!savePath.exists()) {
savePath.mkdirs();
}
Log.i("DOWNLOAD", "下载文件:" + url + " 保存文件:" + saveName);
HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection();
// Log.i(TAG,"获取到网络请求:"+connection.getResponseCode());
InputStream inputStream = connection.getInputStream();
jar = new File(donwloadPath + saveName + "_tmp.tmp");
jar.createNewFile();
Log.i("DOWNLOAD", "临时保存文件:" + jar.getAbsolutePath());
OutputStream outputStream = new FileOutputStream(jar);
byte[] bytes = new byte[1024];
double size=connection.getContentLength();
double downSize=0;
int len;
while ((len = inputStream.read(bytes)) > 0) {
outputStream.write(bytes, 0, len);
downSize+=len;
if(downloadInterface!=null){
downloadInterface.onDownloading(downSize,size);
}
}
outputStream.close();
inputStream.close();
File oldJar = new File(donwloadPath + saveName);
if (oldJar.exists()) {
oldJar.delete();
}
jar.renameTo(oldJar);
Log.i("DOWNLOAD", "实际保存:" + oldJar.getAbsolutePath() + " " + oldJar.getName());
if (downloadInterface != null) {
downloadInterface.onDownload(oldJar);
}
} catch (Exception e) {
e.printStackTrace();
if (jar != null) {
jar.delete();
}
downloadInterface.onError(e);
}
}
}).start();
}
}