| | |
| | | import java.io.File; |
| | | import java.io.FileOutputStream; |
| | | import java.io.IOException; |
| | | import java.io.InputStream; |
| | | import java.net.HttpURLConnection; |
| | | import java.net.URL; |
| | | import java.sql.Timestamp; |
| | | import java.text.DecimalFormat; |
| | | |
| | |
| | | } |
| | | return file; |
| | | } |
| | | |
| | | public static interface DownLoadCallBack{ |
| | | void sucess(); |
| | | void err(String e); |
| | | } |
| | | |
| | | public static void downLoadFile(String filePath,String url,DownLoadCallBack callBack){ |
| | | try { |
| | | URL u = new URL(url); |
| | | HttpURLConnection conn = (HttpURLConnection) u.openConnection(); |
| | | conn.setConnectTimeout(10000); |
| | | int responeCode = conn.getResponseCode(); |
| | | InputStream is; |
| | | if (responeCode == 200) { |
| | | is = conn.getInputStream(); |
| | | } else { |
| | | //连接失败 |
| | | if(callBack!=null){ |
| | | callBack.err("下载地址错误"); |
| | | } |
| | | return; |
| | | } |
| | | |
| | | int fileSize = conn.getContentLength(); |
| | | if (fileSize < 1 || is == null) { |
| | | //文件大小不对 |
| | | if(callBack!=null){ |
| | | callBack.err("文件大小不对"); |
| | | } |
| | | return; |
| | | } else { |
| | | //下载 |
| | | if (FileUtil.deleteFile(filePath)) {// 删除原来的安装文件再下载 |
| | | FileOutputStream fos = new FileOutputStream(filePath); |
| | | byte[] bytes = new byte[1024]; |
| | | int len = -1; |
| | | while ((len = is.read(bytes)) != -1) { |
| | | fos.write(bytes, 0, len); |
| | | fos.flush(); |
| | | } |
| | | //下载完成 |
| | | if(callBack!=null){ |
| | | callBack.sucess(); |
| | | } |
| | | is.close(); |
| | | fos.close(); |
| | | } |
| | | } |
| | | } catch (Exception e) { |
| | | //下载报错 |
| | | if(callBack!=null){ |
| | | callBack.err(e.getMessage()); |
| | | } |
| | | e.printStackTrace(); |
| | | } |
| | | } |
| | | } |