wpc
2018-11-26 aa82e9973b3d962c325d18ed9407b6b33c4fe554
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package com.ysh.wpc.appupdate.download;
 
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;
 
import android.content.Context;
 
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());
        if (contentLength < 0) {
            listener.update(1);
        }
        // 开始读取
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
            count += len;
            if (listener != null && contentLength >= 0)
                listener.update((int) ((float) count / contentLength * 100));
        }
        if (contentLength < 0) {
            listener.update(100);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
 
        return file;
    }
 
    public interface FileProgressListener {
        public void update(int parent);
    }
}