package com.yeshi.base.utils.downutil; import android.content.Context; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.net.URLConnection; public class DownLoadFile { public File downLoadFile(FileProgressListener listener, String filePath, String _urlStr, Context context) throws Exception { // 准备拼接新的文件名(保存在存储卡后的文件名) // String newFilename = _urlStr.substring(_urlStr.lastIndexOf("/") + 1); // UIUtils.showMiddleToast(context, "文件开始下载"); File file = new File((filePath + "").trim()); // 如果目标文件已经存在,则删除。产生覆盖旧文件的效果 // 构造URL URL url = new URL(_urlStr); System.out.println("下载地址:" + _urlStr); // 打开连接 URLConnection con = url.openConnection(); // 获得文件的长度 int contentLength = con.getContentLength(); if (file.exists() && Math.abs(file.length() - contentLength) < 100) { return file; } else { if (file.exists()) file.delete(); } if (file.exists()) { // file.delete(); } else { try { file.createNewFile(); } catch (IOException e) { e.printStackTrace(); } } System.out.println("长度 :" + contentLength); // 输入流 InputStream is = con.getInputStream(); // 1K的数据缓冲 byte[] bs = new byte[1024]; // 读取到的数据长度 int len; int count = 0; // 输出的文件流 OutputStream os = new FileOutputStream((filePath + "").trim()); // 开始读取 while ((len = is.read(bs)) != -1) { os.write(bs, 0, len); count += len; if (listener != null) listener.update((int) ((float) count / contentLength * 100)); } // 完毕,关闭所有链接 os.close(); is.close(); return file; } public interface FileProgressListener { public void update(int parent); } }