1 package org.codehaus.plexus.util;
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 import java.io.BufferedReader;
59 import java.io.File;
60 import java.io.IOException;
61 import java.io.InputStream;
62 import java.io.OutputStream;
63 import java.io.OutputStreamWriter;
64 import java.io.Reader;
65 import java.io.Writer;
66 import java.net.URL;
67 import java.nio.charset.Charset;
68 import java.nio.file.Files;
69 import java.nio.file.Path;
70 import java.nio.file.Paths;
71 import java.nio.file.StandardOpenOption;
72 import java.security.SecureRandom;
73 import java.text.DecimalFormat;
74 import java.util.ArrayList;
75 import java.util.Arrays;
76 import java.util.List;
77 import java.util.Random;
78
79 import org.codehaus.plexus.util.io.InputStreamFacade;
80 import org.codehaus.plexus.util.io.URLInputStreamFacade;
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 public class FileUtils extends BaseFileUtils {
118
119
120
121 public static final int ONE_KB = 1024;
122
123
124
125
126 public static final int ONE_MB = ONE_KB * ONE_KB;
127
128
129
130
131 public static final int ONE_GB = ONE_KB * ONE_MB;
132
133
134
135
136 public static String FS = File.separator;
137
138
139
140
141
142
143
144 private static final String[] INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME = {":", "*", "?", "\"", "<", ">", "|"};
145
146
147
148
149
150 public static String[] getDefaultExcludes() {
151 return DirectoryScanner.DEFAULTEXCLUDES;
152 }
153
154
155
156
157
158 public static List<String> getDefaultExcludesAsList() {
159 return Arrays.asList(getDefaultExcludes());
160 }
161
162
163
164
165
166
167 public static String getDefaultExcludesAsString() {
168 return StringUtils.join(DirectoryScanner.DEFAULTEXCLUDES, ",");
169 }
170
171
172
173
174
175
176
177 public static String byteCountToDisplaySize(int size) {
178 String displaySize;
179
180 if (size / ONE_GB > 0) {
181 displaySize = String.valueOf(size / ONE_GB) + " GB";
182 } else if (size / ONE_MB > 0) {
183 displaySize = String.valueOf(size / ONE_MB) + " MB";
184 } else if (size / ONE_KB > 0) {
185 displaySize = String.valueOf(size / ONE_KB) + " KB";
186 } else {
187 displaySize = String.valueOf(size) + " bytes";
188 }
189
190 return displaySize;
191 }
192
193
194
195
196
197
198
199 public static String dirname(String filename) {
200 int i = filename.lastIndexOf(File.separator);
201 return (i >= 0 ? filename.substring(0, i) : "");
202 }
203
204
205
206
207
208
209
210 public static String filename(String filename) {
211 int i = filename.lastIndexOf(File.separator);
212 return (i >= 0 ? filename.substring(i + 1) : filename);
213 }
214
215
216
217
218
219
220
221 public static String basename(String filename) {
222 return basename(filename, extension(filename));
223 }
224
225
226
227
228
229
230
231
232 public static String basename(String filename, String suffix) {
233 int i = filename.lastIndexOf(File.separator) + 1;
234 int lastDot = ((suffix != null) && (suffix.length() > 0)) ? filename.lastIndexOf(suffix) : -1;
235
236 if (lastDot >= 0) {
237 return filename.substring(i, lastDot);
238 } else if (i > 0) {
239 return filename.substring(i);
240 } else {
241 return filename;
242 }
243 }
244
245
246
247
248
249
250
251
252 public static String extension(String filename) {
253
254 int lastSep = filename.lastIndexOf(File.separatorChar);
255 int lastDot;
256 if (lastSep < 0) {
257 lastDot = filename.lastIndexOf('.');
258 } else {
259 lastDot = filename.substring(lastSep + 1).lastIndexOf('.');
260 if (lastDot >= 0) {
261 lastDot += lastSep + 1;
262 }
263 }
264
265 if (lastDot >= 0 && lastDot > lastSep) {
266 return filename.substring(lastDot + 1);
267 }
268
269 return "";
270 }
271
272
273
274
275
276
277
278 public static boolean fileExists(String fileName) {
279 File file = new File(fileName);
280 return file.exists();
281 }
282
283
284
285
286
287
288
289
290 public static String fileRead(String file) throws IOException {
291 return fileRead(file, null);
292 }
293
294
295
296
297
298
299
300 public static String fileRead(String file, String encoding) throws IOException {
301 return fileRead(Paths.get(file), encoding);
302 }
303
304
305
306
307
308
309
310
311 public static String fileRead(File file) throws IOException {
312 return fileRead(file, null);
313 }
314
315
316
317
318
319
320
321 public static String fileRead(File file, String encoding) throws IOException {
322 return fileRead(file.toPath(), encoding);
323 }
324
325
326
327
328
329
330
331
332
333
334
335 public static void fileAppend(String fileName, String data) throws IOException {
336 fileAppend(fileName, null, data);
337 }
338
339
340
341
342
343
344
345
346
347
348
349 public static void fileAppend(String fileName, String encoding, String data) throws IOException {
350 fileAppend(Paths.get(fileName), encoding, data);
351 }
352
353 private static void fileAppend(Path path, String encoding, String data) throws IOException {
354 fileWrite(path, encoding, data, StandardOpenOption.APPEND, StandardOpenOption.CREATE);
355 }
356
357
358
359
360
361
362
363
364
365 public static void fileWrite(String fileName, String data) throws IOException {
366 fileWrite(fileName, null, data);
367 }
368
369
370
371
372
373
374
375
376
377 public static void fileWrite(String fileName, String encoding, String data) throws IOException {
378 Path file = (fileName == null) ? null : Paths.get(fileName);
379 fileWrite(file, encoding, data);
380 }
381
382
383
384
385
386
387
388
389
390
391 public static void fileWrite(File file, String data) throws IOException {
392 fileWrite(file, null, data);
393 }
394
395
396
397
398
399
400
401
402
403
404 public static void fileWrite(File file, String encoding, String data) throws IOException {
405 fileWrite(file.toPath(), encoding, data);
406 }
407
408
409
410
411
412
413 public static void fileDelete(String fileName) {
414 File file = new File(fileName);
415 try {
416 NioFiles.deleteIfExists(file);
417 } catch (IOException e) {
418 throw new RuntimeException(e);
419 }
420 }
421
422
423
424
425
426
427
428
429 public static boolean waitFor(String fileName, int seconds) {
430 return waitFor(new File(fileName), seconds);
431 }
432
433
434
435
436
437
438
439
440 public static boolean waitFor(File file, int seconds) {
441 int timeout = 0;
442 int tick = 0;
443 while (!file.exists()) {
444 if (tick++ >= 10) {
445 tick = 0;
446 if (timeout++ > seconds) {
447 return false;
448 }
449 }
450 try {
451 Thread.sleep(100);
452 } catch (InterruptedException ignore) {
453
454 }
455 }
456 return true;
457 }
458
459
460
461
462
463
464
465 public static File getFile(String fileName) {
466 return new File(fileName);
467 }
468
469
470
471
472
473
474
475
476
477
478
479
480 public static String[] getFilesFromExtension(String directory, String[] extensions) {
481 List<String> files = new ArrayList<String>();
482
483 File currentDir = new File(directory);
484
485 String[] unknownFiles = currentDir.list();
486
487 if (unknownFiles == null) {
488 return new String[0];
489 }
490
491 for (String unknownFile : unknownFiles) {
492 String currentFileName = directory + System.getProperty("file.separator") + unknownFile;
493 File currentFile = new File(currentFileName);
494
495 if (currentFile.isDirectory()) {
496
497 if (currentFile.getName().equals("CVS")) {
498 continue;
499 }
500
501
502
503
504 String[] fetchFiles = getFilesFromExtension(currentFileName, extensions);
505 files = blendFilesToVector(files, fetchFiles);
506 } else {
507
508
509 String add = currentFile.getAbsolutePath();
510 if (isValidFile(add, extensions)) {
511 files.add(add);
512 }
513 }
514 }
515
516
517 return files.toArray(new String[0]);
518 }
519
520
521
522
523 private static List<String> blendFilesToVector(List<String> v, String[] files) {
524 for (String file : files) {
525 v.add(file);
526 }
527
528 return v;
529 }
530
531
532
533
534
535 private static boolean isValidFile(String file, String[] extensions) {
536 String extension = extension(file);
537 if (extension == null) {
538 extension = "";
539 }
540
541
542
543
544 for (String extension1 : extensions) {
545 if (extension1.equals(extension)) {
546 return true;
547 }
548 }
549
550 return false;
551 }
552
553
554
555
556
557
558
559
560 public static void mkdir(String dir) {
561 File file = new File(dir);
562
563 if (Os.isFamily(Os.FAMILY_WINDOWS) && !isValidWindowsFileName(file)) {
564 throw new IllegalArgumentException("The file (" + dir
565 + ") cannot contain any of the following characters: \n"
566 + StringUtils.join(INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " "));
567 }
568
569 if (!file.exists()) {
570 file.mkdirs();
571 }
572 }
573
574
575
576
577
578
579
580
581
582 public static boolean contentEquals(final File file1, final File file2) throws IOException {
583 final boolean file1Exists = file1.exists();
584 if (file1Exists != file2.exists()) {
585 return false;
586 }
587
588 if (!file1Exists) {
589
590 return true;
591 }
592
593 if (file1.isDirectory() || file2.isDirectory()) {
594
595 return false;
596 }
597
598 try (InputStream input1 = Files.newInputStream(file1.toPath());
599 InputStream input2 = Files.newInputStream(file2.toPath())) {
600 return IOUtil.contentEquals(input1, input2);
601 }
602 }
603
604
605
606
607
608
609
610
611 public static File toFile(final URL url) {
612 if (url == null || !url.getProtocol().equalsIgnoreCase("file")) {
613 return null;
614 }
615
616 String filename = url.getFile().replace('/', File.separatorChar);
617 int pos = -1;
618 while ((pos = filename.indexOf('%', pos + 1)) >= 0) {
619 if (pos + 2 < filename.length()) {
620 String hexStr = filename.substring(pos + 1, pos + 3);
621 char ch = (char) Integer.parseInt(hexStr, 16);
622 filename = filename.substring(0, pos) + ch + filename.substring(pos + 3);
623 }
624 }
625 return new File(filename);
626 }
627
628
629
630
631
632
633
634
635 public static URL[] toURLs(final File[] files) throws IOException {
636 final URL[] urls = new URL[files.length];
637
638 for (int i = 0; i < urls.length; i++) {
639 urls[i] = files[i].toURI().toURL();
640 }
641
642 return urls;
643 }
644
645
646
647
648
649
650
651
652
653
654
655
656
657 public static String removeExtension(final String filename) {
658 String ext = extension(filename);
659
660 if ("".equals(ext)) {
661 return filename;
662 }
663
664 final int index = filename.lastIndexOf(ext) - 1;
665 return filename.substring(0, index);
666 }
667
668
669
670
671
672
673
674
675
676
677
678
679
680 public static String getExtension(final String filename) {
681 return extension(filename);
682 }
683
684
685
686
687
688
689
690
691
692
693
694
695 public static String removePath(final String filepath) {
696 return removePath(filepath, File.separatorChar);
697 }
698
699
700
701
702
703
704
705
706
707
708
709
710
711 public static String removePath(final String filepath, final char fileSeparatorChar) {
712 final int index = filepath.lastIndexOf(fileSeparatorChar);
713
714 if (-1 == index) {
715 return filepath;
716 }
717
718 return filepath.substring(index + 1);
719 }
720
721
722
723
724
725
726
727
728
729
730
731
732 public static String getPath(final String filepath) {
733 return getPath(filepath, File.separatorChar);
734 }
735
736
737
738
739
740
741
742
743
744
745
746
747
748 public static String getPath(final String filepath, final char fileSeparatorChar) {
749 final int index = filepath.lastIndexOf(fileSeparatorChar);
750 if (-1 == index) {
751 return "";
752 }
753
754 return filepath.substring(0, index);
755 }
756
757
758
759
760
761
762
763
764
765
766
767
768
769 public static void copyFileToDirectory(final String source, final String destinationDirectory) throws IOException {
770 copyFileToDirectory(new File(source), new File(destinationDirectory));
771 }
772
773
774
775
776
777
778
779
780
781
782
783
784
785 public static void copyFileToDirectoryIfModified(final String source, final String destinationDirectory)
786 throws IOException {
787 copyFileToDirectoryIfModified(new File(source), new File(destinationDirectory));
788 }
789
790
791
792
793
794
795
796
797
798
799
800
801
802 public static void copyFileToDirectory(final File source, final File destinationDirectory) throws IOException {
803 if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) {
804 throw new IllegalArgumentException("Destination is not a directory");
805 }
806
807 copyFile(source, new File(destinationDirectory, source.getName()));
808 }
809
810
811
812
813
814
815
816
817
818
819
820
821
822 public static void copyFileToDirectoryIfModified(final File source, final File destinationDirectory)
823 throws IOException {
824 if (destinationDirectory.exists() && !destinationDirectory.isDirectory()) {
825 throw new IllegalArgumentException("Destination is not a directory");
826 }
827
828 copyFileIfModified(source, new File(destinationDirectory, source.getName()));
829 }
830
831
832
833
834
835
836
837
838
839 public static void mkDirs(final File sourceBase, String[] dirs, final File destination) throws IOException {
840 for (String dir : dirs) {
841 File src = new File(sourceBase, dir);
842 File dst = new File(destination, dir);
843 if (NioFiles.isSymbolicLink(src)) {
844 File target = NioFiles.readSymbolicLink(src);
845 NioFiles.createSymbolicLink(dst, target);
846 } else {
847 dst.mkdirs();
848 }
849 }
850 }
851
852
853
854
855
856
857
858
859
860
861
862
863 public static void copyFile(final File source, final File destination) throws IOException {
864
865 if (!source.exists()) {
866 final String message = "File " + source + " does not exist";
867 throw new IOException(message);
868 }
869
870
871 if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
872
873 return;
874 }
875 mkdirsFor(destination);
876
877 doCopyFile(source, destination);
878
879 if (source.length() != destination.length()) {
880 String message = "Failed to copy full contents from " + source + " to " + destination;
881 throw new IOException(message);
882 }
883 }
884
885 private static void doCopyFile(File source, File destination) throws IOException {
886 doCopyFileUsingNewIO(source, destination);
887 }
888
889 private static void doCopyFileUsingNewIO(File source, File destination) throws IOException {
890 NioFiles.copy(source, destination);
891 }
892
893
894
895
896
897
898
899
900
901
902
903
904 public static void linkFile(final File source, final File destination) throws IOException {
905
906 if (!source.exists()) {
907 final String message = "File " + source + " does not exist";
908 throw new IOException(message);
909 }
910
911
912 if (source.getCanonicalPath().equals(destination.getCanonicalPath())) {
913
914 return;
915 }
916 mkdirsFor(destination);
917
918 NioFiles.createSymbolicLink(destination, source);
919 }
920
921
922
923
924
925
926
927
928
929
930
931
932 public static boolean copyFileIfModified(final File source, final File destination) throws IOException {
933 if (isSourceNewerThanDestination(source, destination)) {
934 copyFile(source, destination);
935
936 return true;
937 }
938
939 return false;
940 }
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956 public static void copyURLToFile(final URL source, final File destination) throws IOException {
957 copyStreamToFile(new URLInputStreamFacade(source), destination);
958 }
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974 public static void copyStreamToFile(final InputStreamFacade source, final File destination) throws IOException {
975 mkdirsFor(destination);
976 checkCanWrite(destination);
977
978 try (InputStream input = source.getInputStream();
979 OutputStream output = Files.newOutputStream(destination.toPath())) {
980 IOUtil.copy(input, output);
981 }
982 }
983
984 private static void checkCanWrite(File destination) throws IOException {
985
986 if (destination.exists() && !destination.canWrite()) {
987 final String message = "Unable to open file " + destination + " for writing.";
988 throw new IOException(message);
989 }
990 }
991
992 private static void mkdirsFor(File destination) {
993
994 File parentFile = destination.getParentFile();
995 if (parentFile != null && !parentFile.exists()) {
996 parentFile.mkdirs();
997 }
998 }
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017 public static String normalize(final String path) {
1018 String normalized = path;
1019
1020 while (true) {
1021 int index = normalized.indexOf("//");
1022 if (index < 0) {
1023 break;
1024 }
1025 normalized = normalized.substring(0, index) + normalized.substring(index + 1);
1026 }
1027
1028
1029 while (true) {
1030 int index = normalized.indexOf("/./");
1031 if (index < 0) {
1032 break;
1033 }
1034 normalized = normalized.substring(0, index) + normalized.substring(index + 2);
1035 }
1036
1037
1038 while (true) {
1039 int index = normalized.indexOf("/../");
1040 if (index < 0) {
1041 break;
1042 }
1043 if (index == 0) {
1044 return null;
1045 }
1046 int index2 = normalized.lastIndexOf('/', index - 1);
1047 normalized = normalized.substring(0, index2) + normalized.substring(index + 3);
1048 }
1049
1050
1051 return normalized;
1052 }
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069 public static String catPath(final String lookupPath, final String path) {
1070
1071 int index = lookupPath.lastIndexOf("/");
1072 String lookup = lookupPath.substring(0, index);
1073 String pth = path;
1074
1075
1076 while (pth.startsWith("../")) {
1077 if (lookup.length() > 0) {
1078 index = lookup.lastIndexOf("/");
1079 lookup = lookup.substring(0, index);
1080 } else {
1081
1082 return null;
1083 }
1084
1085 index = pth.indexOf("../") + 3;
1086 pth = pth.substring(index);
1087 }
1088
1089 return new StringBuffer(lookup).append("/").append(pth).toString();
1090 }
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101 public static File resolveFile(final File baseFile, String filename) {
1102 String filenm = filename;
1103 if ('/' != File.separatorChar) {
1104 filenm = filename.replace('/', File.separatorChar);
1105 }
1106
1107 if ('\\' != File.separatorChar) {
1108 filenm = filename.replace('\\', File.separatorChar);
1109 }
1110
1111
1112 if (filenm.startsWith(File.separator) || (Os.isFamily(Os.FAMILY_WINDOWS) && filenm.indexOf(":") > 0)) {
1113 File file = new File(filenm);
1114
1115 try {
1116 file = file.getCanonicalFile();
1117 } catch (final IOException ioe) {
1118
1119 }
1120
1121 return file;
1122 }
1123
1124
1125 final char[] chars = filename.toCharArray();
1126 final StringBuilder sb = new StringBuilder();
1127
1128
1129
1130
1131 int start = 0;
1132 if ('\\' == File.separatorChar) {
1133 sb.append(filenm.charAt(0));
1134 start++;
1135 }
1136
1137 for (int i = start; i < chars.length; i++) {
1138 final boolean doubleSeparator = File.separatorChar == chars[i] && File.separatorChar == chars[i - 1];
1139
1140 if (!doubleSeparator) {
1141 sb.append(chars[i]);
1142 }
1143 }
1144
1145 filenm = sb.toString();
1146
1147
1148 File file = (new File(baseFile, filenm)).getAbsoluteFile();
1149
1150 try {
1151 file = file.getCanonicalFile();
1152 } catch (final IOException ioe) {
1153
1154 }
1155
1156 return file;
1157 }
1158
1159
1160
1161
1162
1163
1164
1165 public static void forceDelete(final String file) throws IOException {
1166 forceDelete(new File(file));
1167 }
1168
1169
1170
1171
1172
1173
1174
1175 public static void forceDelete(final File file) throws IOException {
1176 if (file.isDirectory()) {
1177 deleteDirectory(file);
1178 } else {
1179
1180
1181
1182
1183 boolean filePresent = file.getCanonicalFile().exists();
1184 if (!deleteFile(file) && filePresent) {
1185 final String message = "File " + file + " unable to be deleted.";
1186 throw new IOException(message);
1187 }
1188 }
1189 }
1190
1191
1192
1193
1194
1195
1196
1197
1198 private static boolean deleteFile(File file) throws IOException {
1199 if (file.isDirectory()) {
1200 throw new IOException("File " + file + " isn't a file.");
1201 }
1202
1203 if (!file.delete()) {
1204 if (Os.isFamily(Os.FAMILY_WINDOWS)) {
1205 file = file.getCanonicalFile();
1206 System.gc();
1207 }
1208
1209 try {
1210 Thread.sleep(10);
1211 return file.delete();
1212 } catch (InterruptedException ignore) {
1213 return file.delete();
1214 }
1215 }
1216
1217 return true;
1218 }
1219
1220
1221
1222
1223
1224
1225
1226 public static void forceDeleteOnExit(final File file) throws IOException {
1227 if (!file.exists()) {
1228 return;
1229 }
1230
1231 if (file.isDirectory()) {
1232 deleteDirectoryOnExit(file);
1233 } else {
1234 file.deleteOnExit();
1235 }
1236 }
1237
1238
1239
1240
1241
1242
1243
1244 private static void deleteDirectoryOnExit(final File directory) throws IOException {
1245 if (!directory.exists()) {
1246 return;
1247 }
1248 directory.deleteOnExit();
1249
1250 cleanDirectoryOnExit(directory);
1251 }
1252
1253
1254
1255
1256
1257
1258
1259 private static void cleanDirectoryOnExit(final File directory) throws IOException {
1260 if (!directory.exists()) {
1261 final String message = directory + " does not exist";
1262 throw new IllegalArgumentException(message);
1263 }
1264
1265 if (!directory.isDirectory()) {
1266 final String message = directory + " is not a directory";
1267 throw new IllegalArgumentException(message);
1268 }
1269
1270 IOException exception = null;
1271
1272 final File[] files = directory.listFiles();
1273 for (final File file : files) {
1274 try {
1275 forceDeleteOnExit(file);
1276 } catch (final IOException ioe) {
1277 exception = ioe;
1278 }
1279 }
1280
1281 if (null != exception) {
1282 throw exception;
1283 }
1284 }
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294 public static void forceMkdir(final File file) throws IOException {
1295 if (Os.isFamily(Os.FAMILY_WINDOWS)) {
1296 if (!isValidWindowsFileName(file)) {
1297 throw new IllegalArgumentException("The file (" + file.getAbsolutePath()
1298 + ") cannot contain any of the following characters: \n"
1299 + StringUtils.join(INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME, " "));
1300 }
1301 }
1302
1303 if (file.exists()) {
1304 if (file.isFile()) {
1305 final String message =
1306 "File " + file + " exists and is " + "not a directory. Unable to create directory.";
1307 throw new IOException(message);
1308 }
1309 } else {
1310 if (false == file.mkdirs()) {
1311 final String message = "Unable to create directory " + file;
1312 throw new IOException(message);
1313 }
1314 }
1315 }
1316
1317
1318
1319
1320
1321
1322
1323 public static void deleteDirectory(final String directory) throws IOException {
1324 deleteDirectory(new File(directory));
1325 }
1326
1327
1328
1329
1330
1331
1332
1333 public static void deleteDirectory(final File directory) throws IOException {
1334 if (!directory.exists()) {
1335 return;
1336 }
1337
1338
1339
1340
1341
1342 if (directory.delete()) {
1343 return;
1344 }
1345
1346 cleanDirectory(directory);
1347 if (!directory.delete()) {
1348 final String message = "Directory " + directory + " unable to be deleted.";
1349 throw new IOException(message);
1350 }
1351 }
1352
1353
1354
1355
1356
1357
1358
1359 public static void cleanDirectory(final String directory) throws IOException {
1360 cleanDirectory(new File(directory));
1361 }
1362
1363
1364
1365
1366
1367
1368
1369 public static void cleanDirectory(final File directory) throws IOException {
1370 if (!directory.exists()) {
1371 final String message = directory + " does not exist";
1372 throw new IllegalArgumentException(message);
1373 }
1374
1375 if (!directory.isDirectory()) {
1376 final String message = directory + " is not a directory";
1377 throw new IllegalArgumentException(message);
1378 }
1379
1380 IOException exception = null;
1381
1382 final File[] files = directory.listFiles();
1383
1384 if (files == null) {
1385 return;
1386 }
1387
1388 for (final File file : files) {
1389 try {
1390 forceDelete(file);
1391 } catch (final IOException ioe) {
1392 exception = ioe;
1393 }
1394 }
1395
1396 if (null != exception) {
1397 throw exception;
1398 }
1399 }
1400
1401
1402
1403
1404
1405
1406
1407 public static long sizeOfDirectory(final String directory) {
1408 return sizeOfDirectory(new File(directory));
1409 }
1410
1411
1412
1413
1414
1415
1416
1417 public static long sizeOfDirectory(final File directory) {
1418 if (!directory.exists()) {
1419 final String message = directory + " does not exist";
1420 throw new IllegalArgumentException(message);
1421 }
1422
1423 if (!directory.isDirectory()) {
1424 final String message = directory + " is not a directory";
1425 throw new IllegalArgumentException(message);
1426 }
1427
1428 long size = 0;
1429
1430 final File[] files = directory.listFiles();
1431 for (final File file : files) {
1432 if (file.isDirectory()) {
1433 size += sizeOfDirectory(file);
1434 } else {
1435 size += file.length();
1436 }
1437 }
1438
1439 return size;
1440 }
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453 public static List<File> getFiles(File directory, String includes, String excludes) throws IOException {
1454 return getFiles(directory, includes, excludes, true);
1455 }
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468 public static List<File> getFiles(File directory, String includes, String excludes, boolean includeBasedir)
1469 throws IOException {
1470 List<String> fileNames = getFileNames(directory, includes, excludes, includeBasedir);
1471
1472 List<File> files = new ArrayList<File>();
1473
1474 for (String filename : fileNames) {
1475 files.add(new File(filename));
1476 }
1477
1478 return files;
1479 }
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491 public static List<String> getFileNames(File directory, String includes, String excludes, boolean includeBasedir)
1492 throws IOException {
1493 return getFileNames(directory, includes, excludes, includeBasedir, true);
1494 }
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507 public static List<String> getFileNames(
1508 File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive)
1509 throws IOException {
1510 return getFileAndDirectoryNames(directory, includes, excludes, includeBasedir, isCaseSensitive, true, false);
1511 }
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523 public static List<String> getDirectoryNames(
1524 File directory, String includes, String excludes, boolean includeBasedir) throws IOException {
1525 return getDirectoryNames(directory, includes, excludes, includeBasedir, true);
1526 }
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539 public static List<String> getDirectoryNames(
1540 File directory, String includes, String excludes, boolean includeBasedir, boolean isCaseSensitive)
1541 throws IOException {
1542 return getFileAndDirectoryNames(directory, includes, excludes, includeBasedir, isCaseSensitive, false, true);
1543 }
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558 public static List<String> getFileAndDirectoryNames(
1559 File directory,
1560 String includes,
1561 String excludes,
1562 boolean includeBasedir,
1563 boolean isCaseSensitive,
1564 boolean getFiles,
1565 boolean getDirectories)
1566 throws IOException {
1567 DirectoryScanner scanner = new DirectoryScanner();
1568
1569 scanner.setBasedir(directory);
1570
1571 if (includes != null) {
1572 scanner.setIncludes(StringUtils.split(includes, ","));
1573 }
1574
1575 if (excludes != null) {
1576 scanner.setExcludes(StringUtils.split(excludes, ","));
1577 }
1578
1579 scanner.setCaseSensitive(isCaseSensitive);
1580
1581 scanner.scan();
1582
1583 List<String> list = new ArrayList<String>();
1584
1585 if (getFiles) {
1586 String[] files = scanner.getIncludedFiles();
1587
1588 for (String file : files) {
1589 if (includeBasedir) {
1590 list.add(directory + FileUtils.FS + file);
1591 } else {
1592 list.add(file);
1593 }
1594 }
1595 }
1596
1597 if (getDirectories) {
1598 String[] directories = scanner.getIncludedDirectories();
1599
1600 for (String directory1 : directories) {
1601 if (includeBasedir) {
1602 list.add(directory + FileUtils.FS + directory1);
1603 } else {
1604 list.add(directory1);
1605 }
1606 }
1607 }
1608
1609 return list;
1610 }
1611
1612
1613
1614
1615
1616
1617
1618
1619 public static void copyDirectory(File sourceDirectory, File destinationDirectory) throws IOException {
1620 copyDirectory(sourceDirectory, destinationDirectory, "**", null);
1621 }
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633 public static void copyDirectory(File sourceDirectory, File destinationDirectory, String includes, String excludes)
1634 throws IOException {
1635 if (!sourceDirectory.exists()) {
1636 return;
1637 }
1638
1639 List<File> files = getFiles(sourceDirectory, includes, excludes);
1640
1641 for (File file : files) {
1642 copyFileToDirectory(file, destinationDirectory);
1643 }
1644 }
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662 public static void copyDirectoryLayout(
1663 File sourceDirectory, File destinationDirectory, String[] includes, String[] excludes) throws IOException {
1664 if (sourceDirectory == null) {
1665 throw new IOException("source directory can't be null.");
1666 }
1667
1668 if (destinationDirectory == null) {
1669 throw new IOException("destination directory can't be null.");
1670 }
1671
1672 if (sourceDirectory.equals(destinationDirectory)) {
1673 throw new IOException("source and destination are the same directory.");
1674 }
1675
1676 if (!sourceDirectory.exists()) {
1677 throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ").");
1678 }
1679
1680 DirectoryScanner scanner = new DirectoryScanner();
1681
1682 scanner.setBasedir(sourceDirectory);
1683
1684 if (includes != null && includes.length >= 1) {
1685 scanner.setIncludes(includes);
1686 } else {
1687 scanner.setIncludes(new String[] {"**"});
1688 }
1689
1690 if (excludes != null && excludes.length >= 1) {
1691 scanner.setExcludes(excludes);
1692 }
1693
1694 scanner.addDefaultExcludes();
1695 scanner.scan();
1696 List<String> includedDirectories = Arrays.asList(scanner.getIncludedDirectories());
1697
1698 for (String name : includedDirectories) {
1699 File source = new File(sourceDirectory, name);
1700
1701 if (source.equals(sourceDirectory)) {
1702 continue;
1703 }
1704
1705 File destination = new File(destinationDirectory, name);
1706 destination.mkdirs();
1707 }
1708 }
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723 public static void copyDirectoryStructure(File sourceDirectory, File destinationDirectory) throws IOException {
1724 copyDirectoryStructure(sourceDirectory, destinationDirectory, destinationDirectory, false);
1725 }
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740 public static void copyDirectoryStructureIfModified(File sourceDirectory, File destinationDirectory)
1741 throws IOException {
1742 copyDirectoryStructure(sourceDirectory, destinationDirectory, destinationDirectory, true);
1743 }
1744
1745 private static void copyDirectoryStructure(
1746 File sourceDirectory, File destinationDirectory, File rootDestinationDirectory, boolean onlyModifiedFiles)
1747 throws IOException {
1748 if (sourceDirectory == null) {
1749 throw new IOException("source directory can't be null.");
1750 }
1751
1752 if (destinationDirectory == null) {
1753 throw new IOException("destination directory can't be null.");
1754 }
1755
1756 if (sourceDirectory.equals(destinationDirectory)) {
1757 throw new IOException("source and destination are the same directory.");
1758 }
1759
1760 if (!sourceDirectory.exists()) {
1761 throw new IOException("Source directory doesn't exists (" + sourceDirectory.getAbsolutePath() + ").");
1762 }
1763
1764 File[] files = sourceDirectory.listFiles();
1765
1766 String sourcePath = sourceDirectory.getAbsolutePath();
1767
1768 for (File file : files) {
1769 if (file.equals(rootDestinationDirectory)) {
1770
1771 continue;
1772 }
1773
1774 String dest = file.getAbsolutePath();
1775
1776 dest = dest.substring(sourcePath.length() + 1);
1777
1778 File destination = new File(destinationDirectory, dest);
1779
1780 if (file.isFile()) {
1781 destination = destination.getParentFile();
1782
1783 if (onlyModifiedFiles) {
1784 copyFileToDirectoryIfModified(file, destination);
1785 } else {
1786 copyFileToDirectory(file, destination);
1787 }
1788 } else if (file.isDirectory()) {
1789 if (!destination.exists() && !destination.mkdirs()) {
1790 throw new IOException(
1791 "Could not create destination directory '" + destination.getAbsolutePath() + "'.");
1792 }
1793
1794 copyDirectoryStructure(file, destination, rootDestinationDirectory, onlyModifiedFiles);
1795 } else {
1796 throw new IOException("Unknown file type: " + file.getAbsolutePath());
1797 }
1798 }
1799 }
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812 public static void rename(File from, File to) throws IOException {
1813 if (to.exists() && !to.delete()) {
1814 throw new IOException("Failed to delete " + to + " while trying to rename " + from);
1815 }
1816
1817 File parent = to.getParentFile();
1818 if (parent != null && !parent.exists() && !parent.mkdirs()) {
1819 throw new IOException("Failed to create directory " + parent + " while trying to rename " + from);
1820 }
1821
1822 if (!from.renameTo(to)) {
1823 copyFile(from, to);
1824 if (!from.delete()) {
1825 throw new IOException("Failed to delete " + from + " while trying to rename it.");
1826 }
1827 }
1828 }
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848 public static File createTempFile(String prefix, String suffix, File parentDir) {
1849 File result = null;
1850 String parent = System.getProperty("java.io.tmpdir");
1851 if (parentDir != null) {
1852 parent = parentDir.getPath();
1853 }
1854 DecimalFormat fmt = new DecimalFormat("#####");
1855 SecureRandom secureRandom = new SecureRandom();
1856 long secureInitializer = secureRandom.nextLong();
1857 Random rand = new Random(secureInitializer + Runtime.getRuntime().freeMemory());
1858 synchronized (rand) {
1859 do {
1860 result = new File(parent, prefix + fmt.format(Math.abs(rand.nextInt())) + suffix);
1861 } while (result.exists());
1862 }
1863
1864 return result;
1865 }
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876 public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers) throws IOException {
1877 copyFile(from, to, encoding, wrappers, false);
1878 }
1879
1880 public abstract static class FilterWrapper {
1881 public abstract Reader getReader(Reader fileReader);
1882 }
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895 public static void copyFile(File from, File to, String encoding, FilterWrapper[] wrappers, boolean overwrite)
1896 throws IOException {
1897 if (wrappers != null && wrappers.length > 0) {
1898
1899 Reader fileReader = null;
1900 Writer fileWriter = null;
1901 try {
1902 if (encoding == null || encoding.length() < 1) {
1903 fileReader = Files.newBufferedReader(from.toPath());
1904 fileWriter = Files.newBufferedWriter(to.toPath());
1905 } else {
1906 OutputStream outstream = Files.newOutputStream(to.toPath());
1907
1908 fileReader = Files.newBufferedReader(from.toPath(), Charset.forName(encoding));
1909
1910 fileWriter = new OutputStreamWriter(outstream, encoding);
1911 }
1912
1913 Reader reader = fileReader;
1914 for (FilterWrapper wrapper : wrappers) {
1915 reader = wrapper.getReader(reader);
1916 }
1917
1918 IOUtil.copy(reader, fileWriter);
1919 fileWriter.close();
1920 fileWriter = null;
1921 fileReader.close();
1922 fileReader = null;
1923 } finally {
1924 IOUtil.close(fileReader);
1925 IOUtil.close(fileWriter);
1926 }
1927 } else {
1928 if (isSourceNewerThanDestination(from, to) || overwrite) {
1929 copyFile(from, to);
1930 }
1931 }
1932 }
1933
1934 private static boolean isSourceNewerThanDestination(File source, File destination) {
1935 return (destination.lastModified() == 0L && source.lastModified() == 0L)
1936 || destination.lastModified() < source.lastModified();
1937 }
1938
1939
1940
1941
1942
1943
1944
1945
1946 public static List<String> loadFile(File file) throws IOException {
1947 final List<String> lines = new ArrayList<String>();
1948
1949 if (file.exists()) {
1950 try (BufferedReader reader = Files.newBufferedReader(file.toPath())) {
1951 for (String line = reader.readLine(); line != null; line = reader.readLine()) {
1952 line = line.trim();
1953
1954 if (!line.startsWith("#") && line.length() != 0) {
1955 lines.add(line);
1956 }
1957 }
1958 }
1959 }
1960
1961 return lines;
1962 }
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974 public static boolean isValidWindowsFileName(File f) {
1975 if (Os.isFamily(Os.FAMILY_WINDOWS)) {
1976 if (StringUtils.indexOfAny(f.getName(), INVALID_CHARACTERS_FOR_WINDOWS_FILE_NAME) != -1) {
1977 return false;
1978 }
1979
1980 File parentFile = f.getParentFile();
1981 if (parentFile != null) {
1982 return isValidWindowsFileName(parentFile);
1983 }
1984 }
1985
1986 return true;
1987 }
1988 }