基于Android下载并解压Zip文件,更新UI简单帮助类

下载文件:

?
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
<code class = "hljs" java= "" > /**
      * 下载文件
      *
      * @param down_url
      * @param output
      * @param tmpDir
      */
     private void download(String down_url, File output, File tmpDir)
     {
         InputStream inputStream = null ;
         OutputStream outputStream = null ;
         File tmp = null ;
 
         int down_step = 1 ; // 提示step
         int totalSize = 0 ;
         int downloadCount = 0 ; // 已经下载好的大小
         int updateCount = 0 ; // 已经上传的文件大小
 
         try
         {
             tmp = File.createTempFile(download, .tmp, tmpDir);
 
             URL url = new URL(down_url);
             HttpURLConnection httpURLConnection = (HttpURLConnection) url
                     .openConnection();
             httpURLConnection.setConnectTimeout( 30 * 1000 );
             httpURLConnection.setReadTimeout( 30 * 1000 );
             // 获取下载文件的size
             totalSize = httpURLConnection.getContentLength();
 
             inputStream = new URL(down_url).openStream();
             outputStream = new BufferedOutputStream( new FileOutputStream(tmp));
 
             byte [] buffer = new byte [BUFFER_SIZE];
             int readsize = 0 ;
 
             while ((readsize = inputStream.read(buffer)) != - 1 )
             {
                 outputStream.write(buffer, 0 , readsize);
                 downloadCount += readsize; // 时时获取下载到的大小
                 // 每次增长1%
                 if (updateCount == 0
                         || (downloadCount * 100 / totalSize - down_step) >= updateCount)
                 {
                     updateCount += down_step;
 
                     sendMessage(DOWN_UPDATA, updateCount);
                 }
             }
 
             if (httpURLConnection != null )
             {
                 httpURLConnection.disconnect();
             }
             tmp.renameTo(output);
             tmp = null ;
         } catch (IOException e)
         {
             sendMessage(DOWN_ERROR, 0 );
             throw new RuntimeException(e);
         } finally
         {
             try
             {
                 if (tmp != null )
                 {
                     tmp.delete();
                     tmp = null ;
                 }
                 if (inputStream != null )
                 {
                     inputStream.close();
                     inputStream = null ;
                 }
                 if (outputStream != null )
                 {
                     outputStream.close();
                     outputStream = null ;
                 }
             } catch (Exception e2)
             {
                 sendMessage(DOWN_ERROR, 0 );
             }
 
             sendMessage(DOWN_FINISH, 0 );
         }
     }</code>

解压Zip文件

?
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
<code class = "hljs" java= "" > public class ZipUnPack {
     private static final int BUFFER_SIZE = 8192 ;
 
     private String _zipFile;
     private String _location;
     private byte [] _buffer;
 
     /**
      * Constructor.
      *
      * @param zipFile
      *            Fully-qualified path to .zip file
      * @param location
      *            Fully-qualified path to folder where files should be written.
      *            Path must have a trailing slash.
      */
     public ZipUnPack(String zipFile, String location) {
         _zipFile = zipFile;
         _location = location;
         _buffer = new byte [BUFFER_SIZE];
         dirChecker();
     }
 
 
     public Boolean unzip() {
         FileInputStream fin = null ;
         ZipInputStream zin = null ;
         OutputStream fout = null ;
 
         File outputDir = new File(_location);
         File tmp = null ;
 
         Boolean isSucess = true ;
         try {
             fin = new FileInputStream(_zipFile);
             zin = new ZipInputStream(fin);
             ZipEntry ze = null ;
             while ((ze = zin.getNextEntry()) != null ) {
                 Log.d(Decompress, Unzipping  + ze.getName());
 
                 if (ze.isDirectory()) {
                     dirChecker(ze.getName());
                 } else {
                     tmp = File.createTempFile(decomp, .tmp, outputDir);
                     fout = new BufferedOutputStream( new FileOutputStream(tmp));
                     copyStream(zin, fout, _buffer, BUFFER_SIZE);
                     zin.closeEntry();
                     fout.close();
                     fout = null ;
                     tmp.renameTo( new File(_location + ze.getName()));
                     tmp = null ;
                 }
             }
             zin.close();
             zin = null ;
         } catch (IOException e) {
             isSucess = false ;
             throw new RuntimeException(e);
         } finally {
             if (tmp != null ) {
                 try {
                     tmp.delete();
                 } catch (Exception ignore) {
 
                 }
             }
             if (fout != null ) {
                 try {
                     fout.close();
                 } catch (Exception ignore) {
                     ;
                 }
             }
             if (zin != null ) {
                 try {
                     zin.closeEntry();
                 } catch (Exception ignore) {
                     ;
                 }
             }
             if (fin != null ) {
                 try {
                     fin.close();
                 } catch (Exception ignore) {
                     ;
                 }
             }
 
             isSucess = true ;
         }
 
         return isSucess;
     }
 
     private void dirChecker(String dir) {
         File f = new File(_location + dir);
 
         if (!f.isDirectory()) {
             f.mkdirs();
         }
     }
 
 
     /**
      * Copy from one stream to another. Throws IOException in the event of error
      * (for example, SD card is full)
      *
      * @param is
      *            Input stream.
      * @param os
      *            Output stream.
      * @param buffer
      *            Temporary buffer to use for copy.
      * @param bufferSize
      *            Size of temporary buffer, in bytes.
      */
     private void copyStream(InputStream is, OutputStream os,
             byte [] buffer, int bufferSize) throws IOException {
         try {
             for (;;) {
                 int count = is.read(buffer, 0 , bufferSize);
                 if (count == - 1 ) {
                     break ;
                 }
                 os.write(buffer, 0 , count);
             }
         } catch (IOException e) {
             throw e;
         }
     }
}</code>

整个帮助类:

?
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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
<code class = "hljs" java= "" > public class ZipDownLoadHelper
{
 
     private static final int BUFFER_SIZE = 1024 ;
 
     private static final int DOWN_BEGIN = 0 ;
     private static final int DOWN_UPDATA = 1 ;
     private static final int DOWN_FINISH = 2 ;
     private static final int DOWN_ERROR = 3 ;
     private static final int UNPACK_BEGIN = 4 ;
     private static final int UNPACK_END = 5 ;
     private static final int UNPACK_ERROR = 6 ;
 
     private Context mContext;
 
     private Thread mDownLoadThread;
 
     private OnZipDownLoadAndUnpackListener mOnZipDownLoadAndUnpackListener;
 
     private Handler handler = new Handler()
     {
         public void handleMessage(Message msg)
         {
             if (!Thread.currentThread().isInterrupted())
             {
                 switch (msg.what)
                 {
                     case DOWN_BEGIN :
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener.onDownLoadStart();
                         }
 
                         break ;
                     case DOWN_UPDATA :
                         int factor = msg.arg1;
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener
                                     .onDownLoading(factor);
                         }
 
                         break ;
 
                     case DOWN_FINISH :
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener.onDownLoadFinish();
                         }
 
                         break ;
                     case DOWN_ERROR :
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener.onDownLoadError();
                         }
 
                         break ;
                     case UNPACK_BEGIN :
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener.onZipUnpackStart();
                         }
                         break ;
                     case UNPACK_END :
 
                         if (mOnZipDownLoadAndUnpackListener != null )
                         {
                             mOnZipDownLoadAndUnpackListener.onZipUnpackFinish();
                         }
 
                         break ;
                     case UNPACK_ERROR:
 
                         break ;
 
                     default :
                         break ;
                 }
             }
         };
     };
 
     public ZipDownLoadHelper(Context context)
     {
         this .mContext = context;
     }
 
     /**
      * 开启线程
      *
      * @param url
      */
     public void startDownLoadAndZip( final String url)
     {
         mDownLoadThread = new Thread()
         {
             @Override
             public void run()
             {
                 sendMessage(DOWN_BEGIN, 0 );
                 // Temp folder for holding asset during download
                 File zipDir = ExternalStorage.getSDCacheDir(mContext, tmp);
 
                 // File path to store .zip file before unzipping
                 File zipFile = new File(zipDir.getPath() + /temp.zip);
 
                 // Folder to hold unzipped output
                 File outputDir = ExternalStorage.getSDCacheDir(mContext,
                         wms);
 
                 try
                 {
                     download(url, zipFile, zipDir);
                     unzipFile(zipFile, outputDir);
                 } finally
                 {
                     zipFile.delete();
                 }
             }
         };
         mDownLoadThread.start();
     }
 
     @SuppressWarnings (deprecation)
     public void destroyThread()
     {
         mDownLoadThread.stop();
     }
 
     /**
      * 下载文件
      *
      * @param down_url
      * @param output
      * @param tmpDir
      */
     private void download(String down_url, File output, File tmpDir)
     {
         InputStream inputStream = null ;
         OutputStream outputStream = null ;
         File tmp = null ;
 
         int down_step = 1 ; // 提示step
         int totalSize = 0 ;
         int downloadCount = 0 ; // 已经下载好的大小
         int updateCount = 0 ; // 已经上传的文件大小
 
         try
         {
             tmp = File.createTempFile(download, .tmp, tmpDir);
 
             URL url = new URL(down_url);
             HttpURLConnection httpURLConnection = (HttpURLConnection) url
                     .openConnection();
             httpURLConnection.setConnectTimeout( 30 * 1000 );
             httpURLConnection.setReadTimeout( 30 * 1000 );
             // 获取下载文件的size
             totalSize = httpURLConnection.getContentLength();
 
             inputStream = new URL(down_url).openStream();
             outputStream = new BufferedOutputStream( new FileOutputStream(tmp));
 
             byte [] buffer = new byte [BUFFER_SIZE];
             int readsize = 0 ;
 
             while ((readsize = inputStream.read(buffer)) != - 1 )
             {
                 outputStream.write(buffer, 0 , readsize);
                 downloadCount += readsize; // 时时获取下载到的大小
                 // 每次增长1%
                 if (updateCount == 0
                         || (downloadCount * 100 / totalSize - down_step) >= updateCount)
                 {
                     updateCount += down_step;
 
                     sendMessage(DOWN_UPDATA, updateCount);
                 }
             }
 
             if (httpURLConnection != null )
             {
                 httpURLConnection.disconnect();
             }
             tmp.renameTo(output);
             tmp = null ;
         } catch (IOException e)
         {
             sendMessage(DOWN_ERROR, 0 );
             throw new RuntimeException(e);
         } finally
         {
             try
             {
                 if (tmp != null )
                 {
                     tmp.delete();
                     tmp = null ;
                 }
                 if (inputStream != null )
                 {
                     inputStream.close();
                     inputStream = null ;
                 }
                 if (outputStream != null )
                 {
                     outputStream.close();
                     outputStream = null ;
                 }
             } catch (Exception e2)
             {
                 sendMessage(DOWN_ERROR, 0 );
             }
 
             sendMessage(DOWN_FINISH, 0 );
         }
     }
 
     private void sendMessage( int flag, int factor)
     {
         Message msg = new Message();
         switch (flag)
         {
 
             case DOWN_BEGIN : // 开始
             case DOWN_FINISH : // 完成
             case DOWN_ERROR : // 失败
             case UNPACK_BEGIN :
             case UNPACK_END :
             case UNPACK_ERROR:
 
                 break ;
             case DOWN_UPDATA : // 更新进度条
                 msg.arg1 = factor;
                 break ;
 
             default :
                 break ;
         }
         msg.what = flag;
         handler.sendMessage(msg);
     }
 
     /**
      * 解压文件
      *
      * @param zipFile
      * @param destination
      */
     private void unzipFile(File zipFile, File destination)
     {
         sendMessage(UNPACK_BEGIN, 0 );
         ZipUnPack decomp = new ZipUnPack(zipFile.getPath(),
                 destination.getPath() + File.separator);
         Boolean isOk = decomp.unzip();
         if (!isOk)
         {
             sendMessage(UNPACK_ERROR, 0 );
         }
         else
         {
             sendMessage(UNPACK_END, 0 );
         }
 
     }
 
     /**
      * 绑定监听
      *
      * @param listener
      */
     public void setOnZipDownLoadAndUnpackListener(
             OnZipDownLoadAndUnpackListener listener)
     {
         this .mOnZipDownLoadAndUnpackListener = listener;
     }
 
     public interface OnZipDownLoadAndUnpackListener
     {
 
         /**
          * 下载开始
          */
         public void onDownLoadStart();
 
         /**
          * 下载更新
          *
          * @param factor
          */
         public void onDownLoading( int factor);
 
         /**
          * 下载失败
          */
         public void onDownLoadError();
 
         /**
          * 下载完成
          */
         public void onDownLoadFinish();
 
         /**
          * 解压开始
          */
         public void onZipUnpackStart();
 
         /**
          * 解压失败
          */
         public void onZipUnpackError();
 
         /**
          * 解压完成
          */
         public void onZipUnpackFinish();
     }
 
}
</code>

没有认真地检查,可能有bug,使用的伙伴请自己debug下,并通知我一下,谢谢

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值