FileUtils.java
18.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
package com.cnlive.gundam.user.util;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Environment;
import android.os.StatFs;
import android.os.storage.StorageManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import com.cnlive.libs.util.SharedPreferencesHelper;
import org.jivesoftware.smack.util.StringUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Array;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Locale;
import java.util.Map;
public class FileUtils {
// http://www.fileinfo.com/filetypes/video , "dat" , "bin" , "rms"
public static final String[] VIDEO_EXTENSIONS = {"264", "3g2", "3gp",
"3gp2", "3gpp", "3gpp2", "3mm", "3p2", "60d", "aep", "ajp", "amv",
"amx", "arf", "asf", "asx", "avb", "avd", "avi", "avs", "avs",
"axm", "bdm", "bdmv", "bik", "bix", "bmk", "box", "bs4", "bsf",
"byu", "camre", "clpi", "cpi", "cvc", "d2v", "d3v", "dav", "dce",
"dck", "ddat", "dif", "dir", "divx", "dlx", "dmb", "dmsm", "dmss",
"dnc", "dpg", "dream", "dsy", "dv", "dv-avi", "dv4", "dvdmedia",
"dvr-ms", "dvx", "dxr", "dzm", "dzp", "dzt", "evo", "eye", "f4p",
"f4v", "fbr", "fbr", "fbz", "fcp", "flc", "flh", "fli", "flv",
"flx", "gl", "grasp", "gts", "gvi", "gvp", "hdmov", "hkm", "ifo",
"imovi", "imovi", "iva", "ivf", "ivr", "ivs", "izz", "izzy", "jts",
"lsf", "lsx", "m15", "m1pg", "m1v", "m21", "m21", "m2a", "m2p",
"m2t", "m2ts", "m2v", "m4e", "m4u", "m4v", "m75", "meta", "mgv",
"mj2", "mjp", "mjpg", "mkv", "mmv", "mnv", "mod", "modd", "moff",
"moi", "moov", "mov", "movie", "mp21", "mp21", "mp2v", "mp4",
"mp4v", "mpe", "mpeg", "mpeg4", "mpf", "mpg", "mpg2", "mpgin",
"mpl", "mpls", "mpv", "mpv2", "mqv", "msdvd", "msh", "mswmm",
"mts", "mtv", "mvb", "mvc", "mvd", "mve", "mvp", "mxf", "mys",
"ncor", "nsv", "nvc", "ogm", "ogv", "ogx", "osp", "par", "pds",
"pgi", "piv", "playlist", "pmf", "prel", "pro", "prproj", "psh",
"pva", "pvr", "pxv", "qt", "qtch", "qtl", "qtm", "qtz",
"rcproject", "rdb", "rec", "rm", "rmd", "rmp", "rmvb", "roq", "rp",
"rts", "rts", "rum", "rv", "sbk", "sbt", "scm", "scm", "scn",
"sec", "seq", "sfvidcap", "smil", "smk", "sml", "smv", "spl",
"ssm", "str", "stx", "svi", "swf", "swi", "swt", "tda3mt", "tivo",
"tix", "tod", "tp", "tp0", "tpd", "tpr", "trp", "ts", "tvs", "vc1",
"vcr", "vcv", "vdo", "vdr", "veg", "vem", "vf", "vfw", "vfz",
"vgz", "vid", "viewlet", "viv", "vivo", "vlab", "vob", "vp3",
"vp6", "vp7", "vpj", "vro", "vsp", "w32", "wcp", "webm", "wm",
"wmd", "wmmp", "wmv", "wmx", "wp3", "wpl", "wtv", "wvx", "xfl",
"xvid", "yuv", "zm1", "zm2", "zm3", "zmv"};
// http://www.fileinfo.com/filetypes/audio , "spx" , "mid" , "sf"
public static final String[] AUDIO_EXTENSIONS = {"4mp", "669", "6cm",
"8cm", "8med", "8svx", "a2m", "aa", "aa3", "aac", "aax", "abc",
"abm", "ac3", "acd", "acd-bak", "acd-zip", "acm", "act", "adg",
"afc", "agm", "ahx", "aif", "aifc", "aiff", "ais", "akp", "al",
"alaw", "all", "amf", "amr", "ams", "ams", "aob", "ape", "apf",
"apl", "ase", "at3", "atrac", "au", "aud", "aup", "avr", "awb",
"band", "bap", "bdd", "box", "bun", "bwf", "c01", "caf", "cda",
"cdda", "cdr", "cel", "cfa", "cidb", "cmf", "copy", "cpr", "cpt",
"csh", "cwp", "d00", "d01", "dcf", "dcm", "dct", "ddt", "dewf",
"df2", "dfc", "dig", "dig", "dls", "dm", "dmf", "dmsa", "dmse",
"drg", "dsf", "dsm", "dsp", "dss", "dtm", "dts", "dtshd", "dvf",
"dwd", "ear", "efa", "efe", "efk", "efq", "efs", "efv", "emd",
"emp", "emx", "esps", "f2r", "f32", "f3r", "f4a", "f64", "far",
"fff", "flac", "flp", "fls", "frg", "fsm", "fzb", "fzf", "fzv",
"g721", "g723", "g726", "gig", "gp5", "gpk", "gsm", "gsm", "h0",
"hdp", "hma", "hsb", "ics", "iff", "imf", "imp", "ins", "ins",
"it", "iti", "its", "jam", "k25", "k26", "kar", "kin", "kit",
"kmp", "koz", "koz", "kpl", "krz", "ksc", "ksf", "kt2", "kt3",
"ktp", "l", "la", "lqt", "lso", "lvp", "lwv", "m1a", "m3u", "m4a",
"m4b", "m4p", "m4r", "ma1", "mdl", "med", "mgv", "midi", "miniusf",
"mka", "mlp", "mmf", "mmm", "mmp", "mo3", "mod", "mp1", "mp2",
"mp3", "mpa", "mpc", "mpga", "mpu", "mp_", "mscx", "mscz", "msv",
"mt2", "mt9", "mte", "mti", "mtm", "mtp", "mts", "mus", "mws",
"mxl", "mzp", "nap", "nki", "nra", "nrt", "nsa", "nsf", "nst",
"ntn", "nvf", "nwc", "odm", "oga", "ogg", "okt", "oma", "omf",
"omg", "omx", "ots", "ove", "ovw", "pac", "pat", "pbf", "pca",
"pcast", "pcg", "pcm", "peak", "phy", "pk", "pla", "pls", "pna",
"ppc", "ppcx", "prg", "prg", "psf", "psm", "ptf", "ptm", "pts",
"pvc", "qcp", "r", "r1m", "ra", "ram", "raw", "rax", "rbs", "rcy",
"rex", "rfl", "rmf", "rmi", "rmj", "rmm", "rmx", "rng", "rns",
"rol", "rsn", "rso", "rti", "rtm", "rts", "rvx", "rx2", "s3i",
"s3m", "s3z", "saf", "sam", "sb", "sbg", "sbi", "sbk", "sc2", "sd",
"sd", "sd2", "sd2f", "sdat", "sdii", "sds", "sdt", "sdx", "seg",
"seq", "ses", "sf2", "sfk", "sfl", "shn", "sib", "sid", "sid",
"smf", "smp", "snd", "snd", "snd", "sng", "sng", "sou", "sppack",
"sprg", "sseq", "sseq", "ssnd", "stm", "stx", "sty", "svx", "sw",
"swa", "syh", "syw", "syx", "td0", "tfmx", "thx", "toc", "tsp",
"txw", "u", "ub", "ulaw", "ult", "ulw", "uni", "usf", "usflib",
"uw", "uwf", "vag", "val", "vc3", "vmd", "vmf", "vmf", "voc",
"voi", "vox", "vpm", "vqf", "vrf", "vyf", "w01", "wav", "wav",
"wave", "wax", "wfb", "wfd", "wfp", "wma", "wow", "wpk", "wproj",
"wrk", "wus", "wut", "wv", "wvc", "wve", "wwu", "xa", "xa", "xfs",
"xi", "xm", "xmf", "xmi", "xmz", "xp", "xrns", "xsb", "xspf", "xt",
"xwb", "ym", "zvd", "zvr"};
private static final HashSet<String> mHashVideo;
private static final HashSet<String> mHashAudio;
private static final double KB = 1024.0;
private static final double MB = KB * KB;
private static final double GB = KB * KB * KB;
static {
mHashVideo = new HashSet<String>(Arrays.asList(VIDEO_EXTENSIONS));
mHashAudio = new HashSet<String>(Arrays.asList(AUDIO_EXTENSIONS));
}
private static HashMap<String, String> mMimeType = new HashMap<String, String>();
static {
mMimeType.put("M1V", "video/mpeg");
mMimeType.put("MP2", "video/mpeg");
mMimeType.put("MPE", "video/mpeg");
mMimeType.put("MPG", "video/mpeg");
mMimeType.put("MPEG", "video/mpeg");
mMimeType.put("MP4", "video/mp4");
mMimeType.put("M4V", "video/mp4");
mMimeType.put("3GP", "video/3gpp");
mMimeType.put("3GPP", "video/3gpp");
mMimeType.put("3G2", "video/3gpp2");
mMimeType.put("3GPP2", "video/3gpp2");
mMimeType.put("MKV", "video/x-matroska");
mMimeType.put("WEBM", "video/x-matroska");
mMimeType.put("MTS", "video/mp2ts");
mMimeType.put("TS", "video/mp2ts");
mMimeType.put("TP", "video/mp2ts");
mMimeType.put("WMV", "video/x-ms-wmv");
mMimeType.put("ASF", "video/x-ms-asf");
mMimeType.put("ASX", "video/x-ms-asf");
mMimeType.put("FLV", "video/x-flv");
mMimeType.put("MOV", "video/quicktime");
mMimeType.put("QT", "video/quicktime");
mMimeType.put("RM", "video/x-pn-realvideo");
mMimeType.put("RMVB", "video/x-pn-realvideo");
mMimeType.put("VOB", "video/dvd");
mMimeType.put("DAT", "video/dvd");
mMimeType.put("AVI", "video/x-divx");
mMimeType.put("OGV", "video/ogg");
mMimeType.put("OGG", "video/ogg");
mMimeType.put("VIV", "video/vnd.vivo");
mMimeType.put("VIVO", "video/vnd.vivo");
mMimeType.put("WTV", "video/wtv");
mMimeType.put("AVS", "video/avs-video");
mMimeType.put("SWF", "video/x-shockwave-flash");
mMimeType.put("YUV", "video/x-raw-yuv");
}
/**
* 是否是音频或者视频
*/
public static boolean isVideoOrAudio(File f) {
final String ext = getFileExtension(f);
return mHashVideo.contains(ext) || mHashAudio.contains(ext);
}
public static boolean isVideoOrAudio(String f) {
final String ext = getUrlExtension(f);
return mHashVideo.contains(ext) || mHashAudio.contains(ext);
}
public static boolean isVideo(File f) {
final String ext = getFileExtension(f);
return mHashVideo.contains(ext);
}
/**
* 获取文件后缀
*/
public static String getFileExtension(File f) {
if (f != null) {
String filename = f.getName();
int i = filename.lastIndexOf('.');
if (i > 0 && i < filename.length() - 1) {
return filename.substring(i + 1).toLowerCase(Locale.SIMPLIFIED_CHINESE);
}
}
return null;
}
public static String getUrlFileExtensionName(String url) {
if(StringUtils.isEmpty(url)) return "";
int slashIndex = url.lastIndexOf('/');
String filenameWithoutExtension;
filenameWithoutExtension = url.substring(slashIndex + 1);
return filenameWithoutExtension;
}
public static String getUrlFileName(String url) {
int slashIndex = url.lastIndexOf('/');
int dotIndex = url.lastIndexOf('.');
String filenameWithoutExtension;
if (dotIndex == -1) {
filenameWithoutExtension = url.substring(slashIndex + 1);
} else {
filenameWithoutExtension = url.substring(slashIndex + 1, dotIndex);
}
return filenameWithoutExtension;
}
public static String getUrlExtension(String url) {
if (!StringUtils.isEmpty(url)) {
int i = url.lastIndexOf('.');
if (i > 0 && i < url.length() - 1) {
return url.substring(i + 1).toLowerCase(Locale.getDefault());
}
}
return "";
}
public static String getFileNameNoEx(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length()))) {
return filename.substring(0, dot);
}
}
return filename;
}
public static String showFileSize(long size) {
String fileSize;
if (size < KB)
fileSize = size + "B";
else if (size < MB)
fileSize = String.format("%.1f", size / KB) + "KB";
else if (size < GB)
fileSize = String.format("%.1f", size / MB) + "MB";
else
fileSize = String.format("%.1f", size / GB) + "GB";
return fileSize;
}
/**
* 显示SD卡剩余空间
*/
public static String showFileAvailable() {
String result = "";
if (Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState())) {
StatFs sf = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
long blockSize = sf.getBlockSize();
long blockCount = sf.getBlockCount();
long availCount = sf.getAvailableBlocks();
return showFileSize(availCount * blockSize) + " / "
+ showFileSize(blockSize * blockCount);
}
return result;
}
/**
* 如果不存在就创建
*/
public static boolean createIfNoExists(String path) {
File file = new File(path);
boolean mk = false;
if (!file.exists()) {
mk = file.mkdirs();
}
return mk;
}
/**
* 获取MIME
*/
public static String getMimeType(String path) {
int lastDot = path.lastIndexOf(".");
if (lastDot < 0)
return null;
return mMimeType.get(path.substring(lastDot + 1).toUpperCase(Locale.getDefault()));
}
/**
* 多个SD卡时 取外置SD卡
*/
public static String getExternalStorageDirectory() {
// 参考文章
// http://blog.csdn.net/bbmiku/article/details/7937745
Map<String, String> map = System.getenv();
String[] values = new String[map.values().size()];
map.values().toArray(values);
String path = values[values.length - 1];
if (path.startsWith("/mnt/")
&& !Environment.getExternalStorageDirectory().getAbsolutePath()
.equals(path))
return path;
else
return null;
}
public static String getCanonical(File f) {
if (f == null)
return null;
try {
return f.getCanonicalPath();
} catch (IOException e) {
return f.getAbsolutePath();
}
}
public static boolean sdAvailable() {
return Environment.MEDIA_MOUNTED_READ_ONLY.equals(Environment
.getExternalStorageState())
|| Environment.MEDIA_MOUNTED.equals(Environment
.getExternalStorageState());
}
//将SD卡文件删除
public static void deleteFile(File file) {
String sdState = Environment.getExternalStorageState();
if (sdState.equals(Environment.MEDIA_MOUNTED)) {
if (file.exists()) {
if (file.isFile()) {
file.delete();
}
// 如果它是一个目录
else if (file.isDirectory()) {
// 声明目录下所有的文件 files[];
File files[] = file.listFiles();
for (File file1 : files) { // 遍历目录下所有的文件
deleteFile(file1); // 把每个文件 用这个方法进行迭代
}
}
file.delete();
}
}
}
public static long getFileSize(String pathToFile) {
File f = new File(pathToFile);
return f.length();
}
@SuppressLint("DefaultLocale")
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1024 : 1000;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp - 1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
public static String getHumanReadableFileSize(String pathToFile) {
return humanReadableByteCount(getFileSize(pathToFile), true);
}
public static String getDownloadSavePath(Context mContext){
String path;
SharedPreferencesHelper sph = SharedPreferencesHelper.getInstance(mContext);
String downLoadPath = sph.getValue("download_path");
if (downLoadPath != null && !downLoadPath.equals("extra")) {
path = FileUtils.getInnerSDCardPath(mContext);
} else {
path = FileUtils.getExtSDCardPath(mContext);
if(TextUtils.isEmpty(path)){//如果外部存储被拔出,自动转换至内部存储
sph.setValue("download_path","inner");
path = FileUtils.getInnerSDCardPath(mContext);
}
}
return path;
}
public static String readSystem(Context context) {
StatFs stat = new StatFs(getDownloadSavePath(context));
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
long totalSize = totalBlocks * blockSize;
long availSize = availableBlocks * blockSize;
return "可用大小:" + Formatter.formatFileSize(context, availSize) + ",总大小:" + Formatter.formatFileSize(context, totalSize);
}
public static String readExtraSystem(Context context, String path) {
if(TextUtils.isEmpty(path)) return null;
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
long totalSize = totalBlocks * blockSize;
long availSize = availableBlocks * blockSize;
return "可用大小:" + Formatter.formatFileSize(context, availSize);
}
public static String readInnerSystem(Context context) {
String pathStr = "";
if(TextUtils.isEmpty(pathStr = getInnerSDCardPath(context))) return null;
StatFs stat = new StatFs(pathStr);
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
long availableBlocks = stat.getAvailableBlocks();
long totalSize = totalBlocks * blockSize;
long availSize = availableBlocks * blockSize;
return "可用大小:" + Formatter.formatFileSize(context, availSize);
}
/**
* 获取内置SD卡路径
* @return
*/
public static String getInnerSDCardPath(Context context) {
return getStoragePath(context,false);
}
/**
* 获取外置SD卡路径
*
* @return 应该就一条记录或空
*/
public static String getExtSDCardPath(Context context) {
return getStoragePath(context,true);
}
private static String getStoragePath(Context mContext, boolean is_removale) {
StorageManager mStorageManager = (StorageManager) mContext.getSystemService(Context.STORAGE_SERVICE);
Class<?> storageVolumeClazz = null;
try {
storageVolumeClazz = Class.forName("android.os.storage.StorageVolume");
Method getVolumeList = mStorageManager.getClass().getMethod("getVolumeList");
Method getPath = storageVolumeClazz.getMethod("getPath");
Method isRemovable = storageVolumeClazz.getMethod("isRemovable");
Object result = getVolumeList.invoke(mStorageManager);
final int length = Array.getLength(result);
for (int i = 0; i < length; i++) {
Object storageVolumeElement = Array.get(result, i);
String path = (String) getPath.invoke(storageVolumeElement);
boolean removable = (Boolean) isRemovable.invoke(storageVolumeElement);
if (is_removale == removable) {
StatFs stat = new StatFs(path);
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
if(totalBlocks * blockSize <= 0) return null;
return path;
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}