-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileUtils.java
More file actions
715 lines (649 loc) · 21.4 KB
/
FileUtils.java
File metadata and controls
715 lines (649 loc) · 21.4 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
package common.android.fiot.androidcommon;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.os.StatFs;
import android.util.Log;
import android.webkit.MimeTypeMap;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* Created by dinhtho on 14/04/2017.
*/
public class FileUtils {
private static final String TAG = "FileUtils";
/**
* Check SDCard is available
*/
public static boolean isSDCardAvailable() {
return android.os.Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
}
/**
* Checks if external storage is available for read and write
*/
public static boolean isExternalStorageWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/* Checks if external storage is available to at least read */
public static boolean isExternalStorageReadable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) ||
Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
/**
*
* @param context
* @return is Internal Storage Available
*/
public static boolean isInternalStorageAvailable(Context context) {
return new File(context.getFilesDir().toString()).exists();
}
/**
*
* @return SDCard RootPath
*/
public static String getSDCardRootPath() {
if (isSDCardAvailable()) {
return Environment.getExternalStorageDirectory().getAbsolutePath();
}
return null;
}
/**
*
* @param context
* @return Internal Storage Path
*/
public static String getInternalStoragePath(Context context) {
return context.getFilesDir().getAbsolutePath();
}
/**
*
* @return free size External Storage
*/
public static long getFreeSDCardSize() {
if (isSDCardAvailable()) {
File path = new File(getSDCardRootPath());
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return availableBlocks * blockSize;
}
return 0;
}
/**
*
* @param context
* @return free size Internal Storage
*/
public static long getFreeInternalAvailableSize(Context context) {
long freeBytesInternal = new File(context.getFilesDir().getAbsoluteFile().toString()).getFreeSpace();
return freeBytesInternal;
}
public static String getAppFolderInSDCardPath(Context context) {
return getSDCardRootPath() + "/" + context.getResources().getString(R.string.app_name);
}
/**
* Create folder with name is app's name
* @param context
*/
public static void createAppFolderInSDCard(Context context) {
if (isSDCardAvailable()) {
String extStorageDirectory = getSDCardRootPath();
File folder = new File(extStorageDirectory + "/" + context.getResources().getString(R.string.app_name));
Log.i(TAG, "createAppFolderInSDcard: " + folder.getAbsolutePath());
if (!folder.exists()) {
Log.i(TAG, "createAppFolderInSDcard: dd");
folder.mkdir();
}
}
}
/**
* Create folder in Root path of SDCard
* @param nameFolder
*/
public static void createFolderInRootSDCard(String nameFolder) {
if (nameFolder == null || nameFolder.length() == 0) {
return;
} else if (isSDCardAvailable() && isExternalStorageWritable()) {
File f = new File(Environment.getExternalStorageDirectory(), nameFolder);
if (!f.exists()) {
f.mkdirs();
}
}
}
/**
* Create folder in app folder
* @param nameFolder
* @param context
*/
public static void createFolderInAppFolder(String nameFolder, Context context) {
if (nameFolder == null || nameFolder.length() == 0) {
return;
}
if (!isExternalStorageWritable()) return;
createAppFolderInSDCard(context);
createFolder(getAppFolderInSDCardPath(context) + "/" + nameFolder);
}
public static boolean createFolder(String folderPath) {
if (folderPath == null || folderPath.length() == 0) return false;
if (!isExternalStorageWritable()) return false;
File f = new File(folderPath);
if (f.exists() && f.isDirectory()) {
return true;
} else {
return f.mkdirs();
}
}
public static boolean createFolderInInternalStorage(String nameFolder, Context context) {
if (nameFolder == null || nameFolder.length() == 0) {
return false;
}
if (!isInternalStorageAvailable(context)) return false;
File file = new File(context.getFilesDir(), nameFolder);
if (file.exists() && file.isDirectory()) {
return true;
} else {
return file.mkdirs();
}
}
public static void createFileInAppFolder(String fileName, Context context) {
if (fileName == null || fileName.length() == 0) {
return;
}
File f = context.getDir(fileName, Context.MODE_PRIVATE);
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void createFileInRootSDCard(String fileName) {
if (fileName == null || fileName.length() == 0) {
return;
} else if (isSDCardAvailable()) {
File f = new File(Environment.getExternalStorageDirectory(), fileName);
if (!f.exists()) {
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void createFileInternal(String filename, Context context) {
if (filename == null || filename.length() == 0) {
return;
}
File file = new File(context.getFilesDir(), filename);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param f
* @return size file
*/
public static long getFileSize(File f) {
if (!f.exists() || !f.isFile()) {
return 0;
}
return f.length();
}
/**
*
* @param f
* @return kind of f
*/
public static String getFileKind(File f) {
if (!f.exists() || !f.isFile()) {
return null;
}
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(f.getPath());
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
public static long getFileModified(File f) {
if (f.isFile() && f.exists()) {
return f.lastModified();
}
return 0;
}
/**
*
* @param f
* @return Extension of f
*/
public static String getFileExtension(File f) {
if (!f.exists() || !f.isFile()) {
return null;
}
String fileName = f.getName();
String tail = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
if (tail.length() > 0) {
return tail;
}
return null;
}
public static void compressZip(String inputFolderPath, String outZipPath) {
if (!new File(inputFolderPath).exists() || !new File(outZipPath).exists()) {
return;
}
try {
int BUFFER = 2048;
BufferedInputStream origin = null;
FileOutputStream dest = new FileOutputStream(outZipPath);
ZipOutputStream out = new ZipOutputStream(new BufferedOutputStream(dest));
byte data[] = new byte[BUFFER];
File srcFile = new File(inputFolderPath);
if (srcFile.isDirectory()) {
File[] _files = srcFile.listFiles();
for (int i = 0; i < _files.length; i++) {
Log.v("Compress", "Adding: " + _files[i]);
FileInputStream fi = new FileInputStream(_files[i]);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(_files[i].getPath().substring(_files[i].getPath().lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
} else if (srcFile.isFile()) {
Log.v("Compress", "Adding: " + srcFile);
FileInputStream fi = new FileInputStream(srcFile);
origin = new BufferedInputStream(fi, BUFFER);
ZipEntry entry = new ZipEntry(srcFile.getPath().substring(srcFile.getPath().lastIndexOf("/") + 1));
out.putNextEntry(entry);
int count;
while ((count = origin.read(data, 0, BUFFER)) != -1) {
out.write(data, 0, count);
}
origin.close();
}
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param f
* @return checksum file
*/
public static String checksumFile(File f) {
if (!f.exists() || !f.isFile()) {
return null;
}
String returnVal = "";
try {
InputStream input = new FileInputStream(f);
byte[] buffer = new byte[1024];
MessageDigest md5Hash = MessageDigest.getInstance("MD5");
int numRead = 0;
while (numRead != -1) {
numRead = input.read(buffer);
if (numRead > 0) {
md5Hash.update(buffer, 0, numRead);
}
}
input.close();
byte[] md5Bytes = md5Hash.digest();
for (int i = 0; i < md5Bytes.length; i++) {
returnVal += Integer.toString((md5Bytes[i] & 0xff) + 0x100, 16).substring(1);
}
} catch (Throwable t) {
t.printStackTrace();
}
return returnVal.toUpperCase();
}
public static void shareFile(File f, Context context) {
if (!f.exists() || !f.isFile()) {
return;
}
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_EMAIL, f);
sendIntent.setType("text/plain");
context.startActivity(sendIntent);
}
public static void copyfile(File file, File dir) {
if (!file.exists() || !file.isFile() || !dir.exists() || !dir.isDirectory()) {
return;
}
File newFile = new File(dir, file.getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
if (outputChannel != null) try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void douplicateFile(File file) {
if (!file.exists() || !file.isFile()) {
return;
}
int index = 1;
String tail = file.getName().substring(file.getName().lastIndexOf(".") + 1, file.getName().length());
String body = file.getName().substring(0, file.getName().lastIndexOf("."));
String filename = body + "(" + index + ")." + tail;
File f = new File(String.valueOf(file.getParentFile()));
for (int i = 0; i < f.listFiles().length; i++) {
if (filename.equalsIgnoreCase(f.listFiles()[i].getName())) {
index++;
filename = body + "(" + index + ")." + tail;
i = 0;
}
}
File newFile = new File(file.getParentFile(), filename);
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
if (outputChannel != null) try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param f
* @return list files from folder
*/
public static File[] listFolder(File f) {
if (!f.exists() || !f.isDirectory()) {
return null;
}
return f.listFiles();
}
public static void deleteFile(File f) {
if (!f.exists()) {
return;
}
f.delete();
}
public static void moveFile(File file, File dir) {
if (!file.exists() || !file.isFile() || !dir.exists() || !dir.isDirectory()) {
return;
}
File newFile = new File(dir, file.getName());
FileChannel outputChannel = null;
FileChannel inputChannel = null;
try {
outputChannel = new FileOutputStream(newFile).getChannel();
inputChannel = new FileInputStream(file).getChannel();
inputChannel.transferTo(0, inputChannel.size(), outputChannel);
inputChannel.close();
file.delete();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputChannel != null) try {
inputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
if (outputChannel != null) try {
outputChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param f
* @return string in f
*/
public static String readFileString(File f) {
if (!f.exists() || !f.isFile()) {
return null;
}
FileInputStream fin = null;
try {
fin = new FileInputStream(f);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
String ret = null;
try {
ret = convertStreamToString(fin);
} catch (IOException e) {
e.printStackTrace();
}
try {
fin.close();
} catch (IOException e) {
e.printStackTrace();
}
return ret;
}
public static void appendFileString(String data, File f) {
if (data == null) {
return;
}
if(!f.exists()){
try {
f.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
FileWriter fw = null;
try {
fw = new FileWriter(f, true);
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.write(data);
} catch (IOException e) {
e.printStackTrace();
}
try {
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
Boolean firstLine = true;
while ((line = reader.readLine()) != null) {
if (firstLine) {
sb.append(line);
firstLine = false;
} else {
sb.append("\n").append(line);
}
}
reader.close();
return sb.toString();
}
/**
*
* @param f
* @return bytes array
* @throws IOException
*/
public static byte[] readBinaryFile(File f) throws IOException {
if (!f.exists() || !f.isFile()) {
return null;
}
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataOutputStream dos = new DataOutputStream(baos);
byte[] data = new byte[4096];
int count = inputStream.read(data);
while (count != -1) {
dos.write(data, 0, count);
count = inputStream.read(data);
}
return baos.toByteArray();
}
public static void saveStringToSDCard(String data, String nameFile) {
if (nameFile == null || nameFile.length() == 0 || data == null) {
return;
}
if (isSDCardAvailable()) {
File log = new File(Environment.getExternalStorageDirectory(), nameFile);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(log);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
try {
myOutWriter.write(data);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}
} else {
File fp = new File(System.getenv("SECONDARY_STORAGE").toString(), "NewFolder");
fp.mkdir();
if (!fp.exists()) {
return;
}
String secStore = System.getenv("SECONDARY_STORAGE").toString();
File log = new File(secStore, nameFile);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(log);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter myOutWriter =
new OutputStreamWriter(fOut);
try {
myOutWriter.write(data);
myOutWriter.close();
fOut.close();
} catch (Exception e) {
Log.e(TAG, "Error opening Log.", e);
}
}
}
public static void saveBinaryToSDCard(byte[] data, String nameFile) {
if (nameFile == null || nameFile.length() == 0 || data == null) {
return;
}
if (isSDCardAvailable()) {
File log = new File(Environment.getExternalStorageDirectory(), nameFile);
FileOutputStream fOut = null;
try {
fOut = new FileOutputStream(log);
fOut.write(data, 0, data.length);
fOut.flush();
fOut.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
*
* @param dir
* @return size folder
*/
public static long getFolderSize(File dir) {
if (dir.exists() && dir.isDirectory()) {
long result = 0;
File[] fileList = dir.listFiles();
for (int i = 0; i < fileList.length; i++) {
if (fileList[i].isDirectory()) {
result += getFolderSize(fileList[i]);
} else {
result += fileList[i].length();
}
}
return result;
}
return 0;
}
/**
* @param f
* @return epochtime
*/
public static long getFolderModified(File f) {
if (f.exists() && f.isDirectory()) {
return f.lastModified();
}
return 0;
}
}