android 使用URLConnection下载文件

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);
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值