admin
2022-08-09 399ac289f80b7a40aa4210341db6b447cacdcf14
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
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 java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import android.content.Context;
 
public class DownLoadFile {
 
    public File SingleDownload(FileProgressListener listener, String filePath,
                               String _urlStr, Context contex) 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.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
 
        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 (listener != null && 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 (listener != null && contentLength < 0) {
            listener.update(100);
        }
        // 完毕,关闭所有链接
        os.close();
        is.close();
 
        if (file.length() == Long.parseLong(con.getHeaderField("Content-Length"))) {
            return file;
        } else {
            throw new Exception();
        }
    }
 
    public File downLoadFile(FileProgressListener listener, String filePath,
                             String _urlStr, Context context) throws Exception {
        int count = 0;
        while (count < 2) {
            count++;
            try {
                return SingleDownload(listener, filePath, _urlStr, context);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        throw new Exception();
    }
 
    /**
     * 批量下载文件
     *
     * @param urlList
     * @param context
     * @param listener
     */
    public void downloadMultiImages(final List<String> urlList, final List<String> filePathList, final Context context, final FileDownLoadListener listener) throws Exception {
        if (urlList == null || filePathList == null || urlList.size() != filePathList.size()) {
            throw new Exception("参数错误");
        }
        final Map<String, File> fileMap = new HashMap<>();
        final int size = urlList.size();
        for (int p = 0; p < urlList.size(); p++) {
            final int i = p;
            new Thread(new Runnable() {
                @Override
                public void run() {
                    final String url = urlList.get(i);
                    final String filePath = filePathList.get(i);
                    try {
                        downLoadFile(new FileProgressListener() {
                            @Override
                            public void update(int parent) {
                                if (parent >= 100) {
                                    fileMap.put(url, new File(filePath));
                                    if (fileMap.size() == size) {
                                        List<File> resultList = new ArrayList<>();
                                        for (String url : urlList) {
                                            if (fileMap.get(url) != null)
                                                resultList.add(fileMap.get(url));
                                        }
                                        listener.process(resultList.size());
                                        listener.finish(resultList);
                                    }
                                }
                            }
                        }, filePathList.get(i), urlList.get(i), context);
                    } catch (Exception e) {//下载失败了
                        fileMap.put(url, null);
                        if (fileMap.size() == size) {
                            List<File> resultList = new ArrayList<>();
                            for (String tempUrl : urlList) {
                                if (fileMap.get(tempUrl) != null)
                                    resultList.add(fileMap.get(tempUrl));
                            }
                            listener.process(resultList.size());
                            listener.finish(resultList);
                        }
                    }
                }
            }).start();
        }
 
    }
 
 
    public interface FileProgressListener {
        void update(int parent);
    }
 
    public interface FileDownLoadListener {
        void finish(List<File> fileList);
 
        void process(int count);
    }
}