This repository has been archived by the owner on Jan 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
FileUtils.java
700 lines (639 loc) · 17.2 KB
/
FileUtils.java
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
package org.xueyao.utils;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.net.URLEncoder;
import sun.misc.BASE64Encoder;
/**
* 文件工具类
*
* @author xuan
* @version $Revision: 1.0 $, $Date: 2012-11-22 上午9:52:05 $
*/
public abstract class FileUtils {
/**
* 文件大小单位:1KB。
*/
public static final long ONE_KB = 1024;
/**
* 文件大小单位:1MB。
*/
public static final long ONE_MB = ONE_KB * ONE_KB;
/**
* 文件大小单位:1GB。
*/
public static final long ONE_GB = ONE_KB * ONE_MB;
private static final int BUFFER_SIZE = 4096;
private static final String FOLDER_SEPARATOR = "/";
private static final char EXTENSION_SEPARATOR = '.';
/**
* 递归取得某个目录下所有的文件
*
* @param path
* 目录
* @return 文件List
*/
public static List<File> getNestedFiles(String path) {
File directory = new File(path);
if (!directory.exists() || !directory.isDirectory()) {
throw new IllegalArgumentException("Nonexistent directory[" + path + "]");
}
return new Recursiver().getFileList(directory);
}
/**
* 把字符串写到文件中
*
* @param path
* 文件路径
* @param str
* 字符串
* @param append
* 是否追加,否的话会覆盖原来的内容
*/
public static void writeString(String path, String str, boolean append) {
FileWriter out = null;
try {
out = new FileWriter(path, append);
out.write(str);
}
catch (IOException e) {
throw new RuntimeException("Could not write String[" + path + "]", e);
}
finally {
close(out);
}
}
/**
* 从文件中读取字符串,使用默认字符集
*
* @param path
* 文件路径
* @return 文件内容的字符串
*/
public static String readString(String path) {
FileInputStream in = null;
ByteArrayOutputStream out = null;
try {
in = new FileInputStream(path);
out = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
return new String(out.toByteArray());
}
catch (IOException e) {
throw new RuntimeException("Could not read String[" + path + "]", e);
}
finally {
close(in);
close(out);
}
}
/**
* 从输入流中读取字符串,使用默认字符集
*
* @param in
* 输入流
* @return 流内容的字符串
*/
public static String readString(InputStream in) {
ByteArrayOutputStream out = null;
try {
out = new ByteArrayOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int length;
while ((length = in.read(buffer)) != -1) {
out.write(buffer, 0, length);
}
return new String(out.toByteArray());
}
catch (IOException e) {
throw new RuntimeException("Could not read stream", e);
}
finally {
close(in);
close(out);
}
}
/**
* 读取指定路径的Properties文件
*
* @param path
* 路径
* @return Properties对象
*/
public static Properties readProperties(String path) {
File file = new File(path);
if (!file.exists()) {
return null;
}
Properties properties = new Properties();
InputStream in = null;
try {
in = new FileInputStream(file);
properties.load(in);
}
catch (IOException e) {
throw new RuntimeException("Could not read Properties[" + path + "]", e);
}
finally {
close(in);
}
return properties;
}
/**
* 从输入流读取Properties对象
*
* @param in
* 输入流
* @return Properties对象
*/
public static Properties readProperties(InputStream in) {
Properties properties = new Properties();
try {
properties.load(in);
}
catch (IOException e) {
throw new RuntimeException("Could not read Properties", e);
}
finally {
close(in);
}
return properties;
}
/**
* 把Properties对象写到指定路径的文件里
*
* @param path
* 路进
* @param properties
* Properties对象
*/
public static void writeProperties(String path, Properties properties) {
OutputStream out = null;
try {
out = new FileOutputStream(path);
properties.store(out, null);
}
catch (IOException e) {
throw new RuntimeException("Could not write Properties[" + path + "]", e);
}
finally {
close(out);
}
}
/**
* 关闭输入流
*
* @param in
* 输入流
*/
public static void close(InputStream in) {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
}
}
/**
* 关闭输出流
*
* @param out
* 输出流
*/
public static void close(OutputStream out) {
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
}
}
/**
* 关闭 Reader
*
* @param in
* Reader
*/
public static void close(Reader in) {
try {
if (in != null) {
in.close();
}
}
catch (IOException e) {
}
}
/**
* 关闭 Writer
*
* @param out
* Writer
*/
public static void close(Writer out) {
try {
if (out != null) {
out.close();
}
}
catch (IOException e) {
}
}
/**
* 关闭 Closeable 对象。
*
* @param closeable
* Closeable 对象
*/
public static void close(Closeable closeable) {
try {
if (closeable != null) {
closeable.close();
}
}
catch (IOException e) {
}
}
/**
* 取得文件的后缀名。
*
* @param fileName
* 文件名
* @return 后缀名
*/
public static String getExtension(String fileName) {
if (Validators.isEmpty(fileName)) {
return null;
}
int pointIndex = fileName.lastIndexOf(".");
return pointIndex > 0 && pointIndex < fileName.length() ? fileName.substring(pointIndex + 1).toLowerCase()
: null;
}
/**
* 复制给定的数组中的内容到输出流中。
*
* @param in
* 需要复制的数组
* @param out
* 复制到的输出流
* @throws IOException
* 当发生 I/O 异常时抛出
*/
public static void copy(byte[] in, OutputStream out) throws IOException {
try {
out.write(in);
}
finally {
try {
out.close();
}
catch (IOException ex) {
}
}
}
/**
* 将以 byte 为单位的文件大小转换为一个可读性更好的文件大小,最终结果精确到一位小数。
*
* @param size
* 以 byte 为单位的文件大小
* @return 更具可读性的文件大小(包括单位:GB、MB、KB、B),例如:102 B、1.5 KB、23.8 MB、34.2 GB
*/
public static String byteCountToDisplaySize(long size) {
String displaySize;
if (size / ONE_GB > 0) {
displaySize = MathUtils.div(size * 1.0, ONE_GB, 1) + " GB";
}
else if (size / ONE_MB > 0) {
displaySize = MathUtils.div(size * 1.0, ONE_MB, 1) + " MB";
}
else if (size / ONE_KB > 0) {
displaySize = MathUtils.div(size * 1.0, ONE_KB, 1) + " KB";
}
else {
displaySize = String.valueOf(size) + " B";
}
return displaySize;
}
private static class Recursiver {
private static ArrayList<File> files = new ArrayList<File>();
public List<File> getFileList(File file) {
File children[] = file.listFiles();
for (int i = 0; i < children.length; i++) {
if (children[i].isDirectory()) {
new Recursiver().getFileList(children[i]);
}
else {
files.add(children[i]);
}
}
return files;
}
}
/**
* @desc:判断指定路径是否存在,如果不存在,根据参数决定是否新建
* @autor:chenssy
* @date:2014年8月7日
*
* @param filePath
* 指定的文件路径
* @param isNew
* true:新建、false:不新建
* @return 存在返回TRUE,不存在返回FALSE
*/
public static boolean isExist(String filePath,boolean isNew){
File file = new File(filePath);
if(!file.exists() && isNew){
return file.mkdirs(); //新建文件路径
}
return false;
}
/**
* 获取文件名,构建结构为 prefix + yyyyMMddHH24mmss + 10位随机数 + suffix + .type
* @autor:chenssy
* @date:2014年8月11日
*
* @param type
* 文件类型
* @param prefix
* 前缀
* @param suffix
* 后缀
* @return
*/
public static String getFileName(String type,String prefix,String suffix){
String date = DateUtils.getCurrentTime("yyyyMMddHH24mmss"); //当前时间
String random = RandomUtils.generateNumberString(10); //10位随机数
//返回文件名
return prefix + date + random + suffix + "." + type;
}
/**
* 获取文件名,文件名构成:当前时间 + 10位随机数 + .type
* @autor:chenssy
* @date:2014年8月11日
*
* @param type
* 文件类型
* @return
*/
public static String getFileName(String type){
return getFileName(type, "", "");
}
/**
* 获取文件名,文件构成:当前时间 + 10位随机数
* @autor:chenssy
* @date:2014年8月11日
*
* @return
*/
public static String getFileName(){
String date = DateUtils.getCurrentTime("yyyyMMddHH24mmss"); //当前时间
String random = RandomUtils.generateNumberString(10); //10位随机数
//返回文件名
return date + random;
}
/**
* 获取指定文件的大小
*
* @param file
* @return
* @throws Exception
*
* @author:chenssy
* @date : 2016年4月30日 下午9:10:12
*/
@SuppressWarnings("resource")
public static long getFileSize(File file) throws Exception {
long size = 0;
if (file.exists()) {
FileInputStream fis = null;
fis = new FileInputStream(file);
size = fis.available();
} else {
file.createNewFile();
}
return size;
}
/**
* 删除所有文件,包括文件夹
*
* @author : chenssy
* @date : 2016年5月23日 下午12:41:08
*
* @param dirpath
*/
public void deleteAll(String dirpath) {
File path = new File(dirpath);
try {
if (!path.exists())
return;// 目录不存在退出
if (path.isFile()) // 如果是文件删除
{
path.delete();
return;
}
File[] files = path.listFiles();// 如果目录中有文件递归删除文件
for (int i = 0; i < files.length; i++) {
deleteAll(files[i].getAbsolutePath());
}
path.delete();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 复制文件或者文件夹
*
* @author : chenssy
* @date : 2016年5月23日 下午12:41:59
*
* @param inputFile
* 源文件
* @param outputFile
* 目的文件
* @param isOverWrite
* 是否覆盖文件
* @throws java.io.IOException
*/
public static void copy(File inputFile, File outputFile, boolean isOverWrite)
throws IOException {
if (!inputFile.exists()) {
throw new RuntimeException(inputFile.getPath() + "源目录不存在!");
}
copyPri(inputFile, outputFile, isOverWrite);
}
/**
* 复制文件或者文件夹
*
* @author : chenssy
* @date : 2016年5月23日 下午12:43:24
*
* @param inputFile
* 源文件
* @param outputFile
* 目的文件
* @param isOverWrite
* 是否覆盖文件
* @throws java.io.IOException
*/
private static void copyPri(File inputFile, File outputFile, boolean isOverWrite) throws IOException {
if (inputFile.isFile()) { //文件
copySimpleFile(inputFile, outputFile, isOverWrite);
} else {
if (!outputFile.exists()) { //文件夹
outputFile.mkdirs();
}
// 循环子文件夹
for (File child : inputFile.listFiles()) {
copy(child, new File(outputFile.getPath() + "/" + child.getName()), isOverWrite);
}
}
}
/**
* 复制单个文件
*
* @author : chenssy
* @date : 2016年5月23日 下午12:44:07
*
* @param inputFile
* 源文件
* @param outputFile
* 目的文件
* @param isOverWrite
* 是否覆盖
* @throws java.io.IOException
*/
private static void copySimpleFile(File inputFile, File outputFile,
boolean isOverWrite) throws IOException {
if (outputFile.exists()) {
if (isOverWrite) { //可以覆盖
if (!outputFile.delete()) {
throw new RuntimeException(outputFile.getPath() + "无法覆盖!");
}
} else {
// 不允许覆盖
return;
}
}
InputStream in = new FileInputStream(inputFile);
OutputStream out = new FileOutputStream(outputFile);
byte[] buffer = new byte[1024];
int read = 0;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
out.close();
}
/**
* 获取文件的MD5
*
* @author : chenssy
* @date : 2016年5月23日 下午12:50:38
*
* @param file
* 文件
* @return
*/
public static String getFileMD5(File file){
if (!file.exists() || !file.isFile()) {
return null;
}
MessageDigest digest = null;
FileInputStream in = null;
byte buffer[] = new byte[1024];
int len;
try {
digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
while ((len = in.read(buffer, 0, 1024)) != -1) {
digest.update(buffer, 0, len);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
return null;
}
BigInteger bigInt = new BigInteger(1, digest.digest());
return bigInt.toString(16);
}
/**
* 获取文件的后缀
*
* @author : chenssy
* @date : 2016年5月23日 下午12:51:59
*
* @param file
* 文件
* @return
*/
public static String getFileSuffix(String file) {
if (file == null) {
return null;
}
int extIndex = file.lastIndexOf(EXTENSION_SEPARATOR);
if (extIndex == -1) {
return null;
}
int folderIndex = file.lastIndexOf(FOLDER_SEPARATOR);
if (folderIndex > extIndex) {
return null;
}
return file.substring(extIndex + 1);
}
/**
* 文件重命名
*
* @author : chenssy
* @date : 2016年5月23日 下午12:56:05
*
* @param oldPath
* 老文件
* @param newPath
* 新文件
*/
public boolean renameDir(String oldPath, String newPath) {
File oldFile = new File(oldPath);// 文件或目录
File newFile = new File(newPath);// 文件或目录
return oldFile.renameTo(newFile);// 重命名
}
/**
* 下载文件时,针对不同浏览器,进行附件名的编码
* @author : simon xue
* @date : 2017年11月28日 下午19:58:05
* @param filename
* 下载文件名
* @param agent
* 客户端浏览器
* @return 编码后的下载附件名
* @throws IOException
*/
public static String encodeDownloadFilename(String filename, String agent)
throws IOException {
if (agent.contains("Firefox")) { // 火狐浏览器
filename = "=?UTF-8?B?"
+ new BASE64Encoder().encode(filename.getBytes("utf-8"))
+ "?=";
filename = filename.replaceAll("\r\n", "");
} else { // IE及其他浏览器
filename = URLEncoder.encode(filename, "utf-8");
filename = filename.replace("+"," ");
}
return filename;
}
}