public class DownLoadUtil {
//下载文件
public static void downloadFile(String FilePath, Context context,DownLoadCallBack downLoadCallBack) {
try{
//下载路径,如果路径无效了,可换成你的下载路径
String url = FilePath;
File bundleFile = new File(context.getFilesDir().getPath(), "/test");
if(!bundleFile.exists()){
bundleFile.mkdirs();
}
String path = bundleFile.getAbsolutePath();
final long startTime = System.currentTimeMillis();
String filename = "";
filename=url.substring(url.lastIndexOf("/") + 1);
//下载函数
Log.d("文件名称",filename);
//获取文件名
URL myURL = new URL(url);
URLConnection conn = myURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
if (is == null) {
downLoadCallBack.onFaile("stream is null");
throw new RuntimeException("stream is null");
}
File file1 = new File(path);
if(!file1.exists()){
file1.mkdirs();
}
//把数据存入路径+文件名
FileOutputStream fos = new FileOutputStream(path+"/"+filename);
byte buf[] = new byte[1024];
int downLoadFileSize = 0;
do{
//循环读取
int numread = is.read(buf);
if (numread == -1)
{
break;
}
fos.write(buf, 0, numread);
downLoadFileSize += numread;
//更新进度条
} while (true);
is.close();
downLoadCallBack.onSucess("sucess:" + filename);
} catch (Exception ex) {
downLoadCallBack.onFaile(ex.getMessage());
Log.d("aaa",ex.getMessage());
}
}
public interface DownLoadCallBack {
void onSucess(String tag);
void onFaile(String tag);
}
}