-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathAbFileUtil.java
More file actions
1238 lines (1153 loc) · 31.9 KB
/
AbFileUtil.java
File metadata and controls
1238 lines (1153 loc) · 31.9 KB
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2012 www.amsoft.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ab.util;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import com.ab.global.AbAppConfig;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
// TODO: Auto-generated Javadoc
/**
* © 2012 amsoft.cn 名称:AbFileUtil.java 描述:文件操作类.
*/
public class AbFileUtil {
/** 默认APP根目录. */
private static String downloadRootDir = null;
/** 默认下载图片文件目录. */
private static String imageDownloadDir = null;
/** 默认下载文件目录. */
private static String fileDownloadDir = null;
/** 默认缓存目录. */
private static String cacheDownloadDir = null;
/** 默认下载数据库文件的目录. */
private static String dbDownloadDir = null;
/** 剩余空间大于200M才使用SD缓存. */
private static int freeSdSpaceNeededToCache = 200 * 1024 * 1024;
/**
* 描述:通过文件的网络地址从SD卡中读取图片,如果SD中没有则自动下载并保存.
*
* @param url
* 文件的网络地址
* @param type
* 图片的处理类型(剪切或者缩放到指定大小,参考AbImageUtil类) 如果设置为原图,则后边参数无效,得到原图
* @param desiredWidth
* 新图片的宽
* @param desiredHeight
* 新图片的高
* @return Bitmap 新图片
*/
public static Bitmap getBitmapFromSD(String url, int type, int desiredWidth, int desiredHeight) {
Bitmap bitmap = null;
try {
if (AbStrUtil.isEmpty(url)) {
return null;
}
// SD卡不存在 或者剩余空间不足了就不缓存到SD卡了
if (!isCanUseSD() || freeSdSpaceNeededToCache < freeSpaceOnSD()) {
bitmap = getBitmapFromURL(url, type, desiredWidth, desiredHeight);
return bitmap;
}
// 下载文件,如果不存在就下载,存在直接返回地址
String downFilePath = downloadFile(url, imageDownloadDir);
if (downFilePath != null) {
// 获取图片
return getBitmapFromSD(new File(downFilePath), type, desiredWidth, desiredHeight);
} else {
return null;
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 描述:通过文件的本地地址从SD卡读取图片.
*
* @param file
* the file
* @param type
* 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类) 如果设置为原图,则后边参数无效,得到原图
* @param desiredWidth
* 新图片的宽
* @param desiredHeight
* 新图片的高
* @return Bitmap 新图片
*/
public static Bitmap getBitmapFromSD(File file, int type, int desiredWidth, int desiredHeight) {
Bitmap bitmap = null;
try {
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 文件是否存在
if (!file.exists()) {
return null;
}
// 文件存在
if (type == AbImageUtil.CUTIMG) {
bitmap = AbImageUtil.cutImg(file, desiredWidth, desiredHeight);
} else if (type == AbImageUtil.SCALEIMG) {
bitmap = AbImageUtil.scaleImg(file, desiredWidth, desiredHeight);
} else {
bitmap = AbImageUtil.getBitmap(file);
}
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 描述:通过文件的本地地址从SD卡读取图片.
*
* @param file
* the file
* @return Bitmap 图片
*/
public static Bitmap getBitmapFromSD(File file) {
Bitmap bitmap = null;
try {
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 文件是否存在
if (!file.exists()) {
return null;
}
// 文件存在
bitmap = AbImageUtil.getBitmap(file);
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
/**
* 描述:将图片的byte[]写入本地文件.
*
* @param imgByte
* 图片的byte[]形势
* @param fileName
* 文件名称,需要包含后缀,如.jpg
* @param type
* 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类)
* @param desiredWidth
* 新图片的宽
* @param desiredHeight
* 新图片的高
* @return Bitmap 新图片
*/
public static Bitmap getBitmapFromByte(byte[] imgByte, String fileName, int type, int desiredWidth,
int desiredHeight) {
FileOutputStream fos = null;
DataInputStream dis = null;
ByteArrayInputStream bis = null;
Bitmap bitmap = null;
File file = null;
try {
if (imgByte != null) {
file = new File(imageDownloadDir + fileName);
if (!file.exists()) {
file.createNewFile();
}
fos = new FileOutputStream(file);
int readLength = 0;
bis = new ByteArrayInputStream(imgByte);
dis = new DataInputStream(bis);
byte[] buffer = new byte[1024];
while ((readLength = dis.read(buffer)) != -1) {
fos.write(buffer, 0, readLength);
try {
Thread.sleep(500);
} catch (Exception e) {
}
}
fos.flush();
bitmap = getBitmapFromSD(file, type, desiredWidth, desiredHeight);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (dis != null) {
try {
dis.close();
} catch (Exception e) {
}
}
if (bis != null) {
try {
bis.close();
} catch (Exception e) {
}
}
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
}
return bitmap;
}
/**
* 描述:根据URL从互连网获取图片.
*
* @param url
* 要下载文件的网络地址
* @param type
* 图片的处理类型(剪切或者缩放到指定大小,参考AbConstant类)
* @param desiredWidth
* 新图片的宽
* @param desiredHeight
* 新图片的高
* @return Bitmap 新图片
*/
public static Bitmap getBitmapFromURL(String url, int type, int desiredWidth, int desiredHeight) {
Bitmap bit = null;
try {
bit = AbImageUtil.getBitmap(url, type, desiredWidth, desiredHeight);
} catch (Exception e) {
AbLogUtil.d(AbFileUtil.class, "下载图片异常:" + e.getMessage());
}
return bit;
}
/**
* 描述:获取src中的图片资源.
*
* @param src
* 图片的src路径,如(“image/arrow.png”)
* @return Bitmap 图片
*/
public static Bitmap getBitmapFromSrc(String src) {
Bitmap bit = null;
try {
bit = BitmapFactory.decodeStream(AbFileUtil.class.getResourceAsStream(src));
} catch (Exception e) {
AbLogUtil.d(AbFileUtil.class, "获取图片异常:" + e.getMessage());
}
return bit;
}
/**
* 描述:获取Asset中的图片资源.
*
* @param context
* the context
* @param fileName
* the file name
* @return Bitmap 图片
*/
public static Bitmap getBitmapFromAsset(Context context, String fileName) {
Bitmap bit = null;
try {
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
bit = BitmapFactory.decodeStream(is);
} catch (Exception e) {
AbLogUtil.d(AbFileUtil.class, "获取图片异常:" + e.getMessage());
}
return bit;
}
/**
* 描述:获取Asset中的图片资源.
*
* @param context
* the context
* @param fileName
* the file name
* @return Drawable 图片
*/
public static Drawable getDrawableFromAsset(Context context, String fileName) {
Drawable drawable = null;
try {
AssetManager assetManager = context.getAssets();
InputStream is = assetManager.open(fileName);
drawable = Drawable.createFromStream(is, null);
} catch (Exception e) {
AbLogUtil.d(AbFileUtil.class, "获取图片异常:" + e.getMessage());
}
return drawable;
}
/**
* 下载网络文件到SD卡中.如果SD中存在同名文件将不再下载
*
* @param url
* 要下载文件的网络地址
* @param dirPath
* the dir path
* @return 下载好的本地文件地址
*/
public static String downloadFile(String url, String dirPath) {
InputStream in = null;
FileOutputStream fileOutputStream = null;
HttpURLConnection connection = null;
String downFilePath = null;
File file = null;
try {
if (!isCanUseSD()) {
return null;
}
// 先判断SD卡中有没有这个文件,不比较后缀部分比较
String fileNameNoMIME = getCacheFileNameFromUrl(url);
File parentFile = new File(imageDownloadDir);
File[] files = parentFile.listFiles();
for (int i = 0; i < files.length; ++i) {
String fileName = files[i].getName();
String name = fileName.substring(0, fileName.lastIndexOf("."));
if (name.equals(fileNameNoMIME)) {
// 文件已存在
return files[i].getPath();
}
}
URL mUrl = new URL(url);
connection = (HttpURLConnection) mUrl.openConnection();
connection.connect();
// 获取文件名,下载文件
String fileName = getCacheFileNameFromUrl(url, connection);
file = new File(imageDownloadDir, fileName);
downFilePath = file.getPath();
if (!file.exists()) {
file.createNewFile();
} else {
// 文件已存在
return file.getPath();
}
in = connection.getInputStream();
fileOutputStream = new FileOutputStream(file);
byte[] b = new byte[1024];
int temp = 0;
while ((temp = in.read(b)) != -1) {
fileOutputStream.write(b, 0, temp);
}
} catch (Exception e) {
e.printStackTrace();
AbLogUtil.e(AbFileUtil.class, "有文件下载出错了,已删除");
// 检查文件大小,如果文件为0B说明网络不好没有下载成功,要将建立的空文件删除
if (file != null) {
file.delete();
}
file = null;
downFilePath = null;
} finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (fileOutputStream != null) {
fileOutputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
try {
if (connection != null) {
connection.disconnect();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return downFilePath;
}
/**
* 描述:获取网络文件的大小.
*
* @param Url
* 图片的网络路径
* @return int 网络文件的大小
*/
public static int getContentLengthFromUrl(String Url) {
int mContentLength = 0;
try {
URL url = new URL(Url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) url.openConnection();
mHttpURLConnection.setConnectTimeout(5 * 1000);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
mHttpURLConnection.setRequestProperty("Referer", Url);
mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
mHttpURLConnection.setRequestProperty("User-Agent",
"Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == 200) {
// 根据响应获取文件大小
mContentLength = mHttpURLConnection.getContentLength();
}
} catch (Exception e) {
e.printStackTrace();
AbLogUtil.d(AbFileUtil.class, "获取长度异常:" + e.getMessage());
}
return mContentLength;
}
/**
* 获取文件名,通过网络获取.
*
* @param url
* 文件地址
* @return 文件名
*/
public static String getRealFileNameFromUrl(String url) {
String name = null;
try {
if (AbStrUtil.isEmpty(url)) {
return name;
}
URL mUrl = new URL(url);
HttpURLConnection mHttpURLConnection = (HttpURLConnection) mUrl.openConnection();
mHttpURLConnection.setConnectTimeout(5 * 1000);
mHttpURLConnection.setRequestMethod("GET");
mHttpURLConnection.setRequestProperty("Accept",
"image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
mHttpURLConnection.setRequestProperty("Accept-Language", "zh-CN");
mHttpURLConnection.setRequestProperty("Referer", url);
mHttpURLConnection.setRequestProperty("Charset", "UTF-8");
mHttpURLConnection.setRequestProperty("User-Agent", "");
mHttpURLConnection.setRequestProperty("Connection", "Keep-Alive");
mHttpURLConnection.connect();
if (mHttpURLConnection.getResponseCode() == 200) {
for (int i = 0;; i++) {
String mine = mHttpURLConnection.getHeaderField(i);
if (mine == null) {
break;
}
if ("content-disposition".equals(mHttpURLConnection.getHeaderFieldKey(i).toLowerCase())) {
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mine.toLowerCase());
if (m.find())
return m.group(1).replace("\"", "");
}
}
}
} catch (Exception e) {
e.printStackTrace();
AbLogUtil.e(AbFileUtil.class, "网络上获取文件名失败");
}
return name;
}
/**
* 获取真实文件名(xx.后缀),通过网络获取.
*
* @param connection
* 连接
* @return 文件名
*/
public static String getRealFileName(HttpURLConnection connection) {
String name = null;
try {
if (connection == null) {
return name;
}
if (connection.getResponseCode() == 200) {
for (int i = 0;; i++) {
String mime = connection.getHeaderField(i);
if (mime == null) {
break;
}
// "Content-Disposition","attachment; filename=1.txt"
// Content-Length
if ("content-disposition".equals(connection.getHeaderFieldKey(i).toLowerCase())) {
Matcher m = Pattern.compile(".*filename=(.*)").matcher(mime.toLowerCase());
if (m.find()) {
return m.group(1).replace("\"", "");
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
AbLogUtil.e(AbFileUtil.class, "网络上获取文件名失败");
}
return name;
}
/**
* 获取文件名(不含后缀).
*
* @param url
* 文件地址
* @return 文件名
*/
public static String getCacheFileNameFromUrl(String url) {
if (AbStrUtil.isEmpty(url)) {
return null;
}
String name = null;
try {
name = AbMd5.MD5(url);
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
/**
* 获取文件名(.后缀),外链模式和通过网络获取.
*
* @param url
* 文件地址
* @param connection
* the connection
* @return 文件名
*/
public static String getCacheFileNameFromUrl(String url, HttpURLConnection connection) {
if (AbStrUtil.isEmpty(url)) {
return null;
}
String name = null;
try {
// 获取后缀
String suffix = getMIMEFromUrl(url, connection);
if (AbStrUtil.isEmpty(suffix)) {
suffix = ".ab";
}
name = AbMd5.MD5(url) + suffix;
} catch (Exception e) {
e.printStackTrace();
}
return name;
}
/**
* 获取文件后缀,本地.
*
* @param url
* 文件地址
* @param connection
* the connection
* @return 文件后缀
*/
public static String getMIMEFromUrl(String url, HttpURLConnection connection) {
if (AbStrUtil.isEmpty(url)) {
return null;
}
String suffix = null;
try {
// 获取后缀
if (url.lastIndexOf(".") != -1) {
suffix = url.substring(url.lastIndexOf("."));
if (suffix.indexOf("/") != -1 || suffix.indexOf("?") != -1 || suffix.indexOf("&") != -1) {
suffix = null;
}
}
if (AbStrUtil.isEmpty(suffix)) {
// 获取文件名 这个效率不高
String fileName = getRealFileName(connection);
if (fileName != null && fileName.lastIndexOf(".") != -1) {
suffix = fileName.substring(fileName.lastIndexOf("."));
}
}
} catch (Exception e) {
e.printStackTrace();
}
return suffix;
}
/**
* 描述:从sd卡中的文件读取到byte[].
*
* @param path
* sd卡中文件路径
* @return byte[]
*/
public static byte[] getByteArrayFromSD(String path) {
byte[] bytes = null;
ByteArrayOutputStream out = null;
try {
File file = new File(path);
// SD卡是否存在
if (!isCanUseSD()) {
return null;
}
// 文件是否存在
if (!file.exists()) {
return null;
}
long fileSize = file.length();
if (fileSize > Integer.MAX_VALUE) {
return null;
}
FileInputStream in = new FileInputStream(path);
out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[1024];
int size = 0;
while ((size = in.read(buffer)) != -1) {
out.write(buffer, 0, size);
}
in.close();
bytes = out.toByteArray();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (out != null) {
try {
out.close();
} catch (Exception e) {
}
}
}
return bytes;
}
/**
* 描述:将byte数组写入文件.
*
* @param path
* the path
* @param content
* the content
* @param create
* the create
*/
public static void writeByteArrayToSD(String path, byte[] content, boolean create) {
FileOutputStream fos = null;
try {
File file = new File(path);
// SD卡是否存在
if (!isCanUseSD()) {
return;
}
// 文件是否存在
if (!file.exists()) {
if (create) {
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
file.createNewFile();
}
} else {
return;
}
}
fos = new FileOutputStream(path);
fos.write(content);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (Exception e) {
}
}
}
}
/**
* 描述:SD卡是否能用.
*
* @return true 可用,false不可用
*/
public static boolean isCanUseSD() {
try {
return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* 描述:初始化存储目录.
*
* @param context
* the context
*/
public static void initFileDir(Context context) {
PackageInfo info = AbAppUtil.getPackageInfo(context);
// 默认下载文件根目录.
String downloadRootPath = File.separator + AbAppConfig.DOWNLOAD_ROOT_DIR + File.separator + info.packageName
+ File.separator;
// 默认下载图片文件目录.
String imageDownloadPath = downloadRootPath + AbAppConfig.DOWNLOAD_IMAGE_DIR + File.separator;
// 默认下载文件目录.
String fileDownloadPath = downloadRootPath + AbAppConfig.DOWNLOAD_FILE_DIR + File.separator;
// 默认缓存目录.
String cacheDownloadPath = downloadRootPath + AbAppConfig.CACHE_DIR + File.separator;
// 默认DB目录.
String dbDownloadPath = downloadRootPath + AbAppConfig.DB_DIR + File.separator;
try {
if (!isCanUseSD()) {
return;
} else {
File root = Environment.getExternalStorageDirectory();
File downloadDir = new File(root.getAbsolutePath() + downloadRootPath);
if (!downloadDir.exists()) {
downloadDir.mkdirs();
}
downloadRootDir = downloadDir.getPath();
File cacheDownloadDirFile = new File(root.getAbsolutePath() + cacheDownloadPath);
if (!cacheDownloadDirFile.exists()) {
cacheDownloadDirFile.mkdirs();
}
cacheDownloadDir = cacheDownloadDirFile.getPath();
File imageDownloadDirFile = new File(root.getAbsolutePath() + imageDownloadPath);
if (!imageDownloadDirFile.exists()) {
imageDownloadDirFile.mkdirs();
}
imageDownloadDir = imageDownloadDirFile.getPath();
File fileDownloadDirFile = new File(root.getAbsolutePath() + fileDownloadPath);
if (!fileDownloadDirFile.exists()) {
fileDownloadDirFile.mkdirs();
}
fileDownloadDir = fileDownloadDirFile.getPath();
File dbDownloadDirFile = new File(root.getAbsolutePath() + dbDownloadPath);
if (!dbDownloadDirFile.exists()) {
dbDownloadDirFile.mkdirs();
}
dbDownloadDir = dbDownloadDirFile.getPath();
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 计算sdcard上的剩余空间.
*
* @return the int
*/
public static int freeSpaceOnSD() {
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
double sdFreeMB = ((double) stat.getAvailableBlocks() * (double) stat.getBlockSize()) / 1024 * 1024;
return (int) sdFreeMB;
}
/**
* 根据文件的最后修改时间进行排序.
*/
public static class FileLastModifSort implements Comparator<File> {
/*
* (non-Javadoc)
*
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(File arg0, File arg1) {
if (arg0.lastModified() > arg1.lastModified()) {
return 1;
} else if (arg0.lastModified() == arg1.lastModified()) {
return 0;
} else {
return -1;
}
}
}
/**
* 删除所有缓存文件.
*
* @return true, if successful
*/
public static boolean clearDownloadFile() {
try {
if (!isCanUseSD()) {
return false;
}
File path = Environment.getExternalStorageDirectory();
File fileDirectory = new File(path.getAbsolutePath() + downloadRootDir);
File[] files = fileDirectory.listFiles();
if (files == null) {
return true;
}
for (int i = 0; i < files.length; i++) {
files[i].delete();
}
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}
/**
* 描述:读取Assets目录的文件内容.
*
* @param context
* the context
* @param name
* the name
* @param encoding
* the encoding
* @return the string
*/
public static String readAssetsByName(Context context, String name, String encoding) {
String text = null;
InputStreamReader inputReader = null;
BufferedReader bufReader = null;
try {
inputReader = new InputStreamReader(context.getAssets().open(name));
bufReader = new BufferedReader(inputReader);
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufReader.readLine()) != null) {
buffer.append(line);
}
text = new String(buffer.toString().getBytes(), encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufReader != null) {
bufReader.close();
}
if (inputReader != null) {
inputReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return text;
}
/**
* 描述:读取Raw目录的文件内容.
*
* @param context
* the context
* @param id
* the id
* @param encoding
* the encoding
* @return the string
*/
public static String readRawByName(Context context, int id, String encoding) {
String text = null;
InputStreamReader inputReader = null;
BufferedReader bufReader = null;
try {
inputReader = new InputStreamReader(context.getResources().openRawResource(id));
bufReader = new BufferedReader(inputReader);
String line = null;
StringBuffer buffer = new StringBuffer();
while ((line = bufReader.readLine()) != null) {
buffer.append(line);
}
text = new String(buffer.toString().getBytes(), encoding);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (bufReader != null) {
bufReader.close();
}
if (inputReader != null) {
inputReader.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return text;
}
/**
* 解压缩功能. 将zipFile文件解压到folderPath目录下.
*
* @param zipFile
* zip文件地址
* @param folderPath
* 解压目的文件
* @return
*/
public int upZipFile(File zipFile, String folderPath) {
try {
ZipFile zfile = new ZipFile(zipFile);
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
Log.d("upZipFile", "ze.getName() = " + ze.getName());
String dirstr = folderPath + ze.getName();
// dirstr.trim();
dirstr = new String(dirstr.getBytes("8859_1"), "GB2312");
Log.d("upZipFile", "str = " + dirstr);
File f = new File(dirstr);
f.mkdir();
continue;
}
Log.d("upZipFile", "ze.getName() = " + ze.getName());
OutputStream os = new BufferedOutputStream(
new FileOutputStream(getRealFileName(folderPath, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
}
zfile.close();
} catch (IOException e) {
Log.e("tag", "解压失败!");
}
return 0;
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.(压缩文件)
*
* @param baseDir
* 指定根目录
* @param absFileName
* 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件